#!/bin/bash
# Copyright (c) 2021 Microsoft Corporation.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Arguments:
#   $1 - kernel version
#   $2 - kernel image file
#   $3 - kernel map file
#   $4 - default install path (blank if root directory)

set -e

KERNEL_VERSION="$1"
KERNEL_IMAGE="$2"
SYSTEM_MAP="$3"
DEST_DIR="${4:-/boot}"

echo installkernel $1 $2 $3 $4

FINAL_KERNEL_IMAGE=vmlinuz-"$KERNEL_VERSION"
FINAL_INITRD=initrd.img-"$KERNEL_VERSION"
FINAL_LINUX_CFG_PATH="$DEST_DIR"/linux-"$KERNEL_VERSION".cfg

# Copy kernel
cp "$KERNEL_IMAGE" "$DEST_DIR"/"$FINAL_KERNEL_IMAGE"
cp "$SYSTEM_MAP" "$DEST_DIR"/System.map-"$KERNEL_VERSION"
cp $(dirname "$SYSTEM_MAP")/.config "$DEST_DIR"/config-"$KERNEL_VERSION"

# Remake initrd
if [ ! -d /lib/modules/"$KERNEL_VERSION" ]; then
	echo Cannot find modules for "$KERNEL_VERSION"
	echo Please run: make modules_install
	exit 1
fi
mkinitrd -q "$DEST_DIR"/"$FINAL_INITRD" "$KERNEL_VERSION" -k

# Create linux cfg file if it doesn't exist
if [ ! -f "$FINAL_LINUX_CFG_PATH" ]; then
	cp -f "$DEST_DIR"/mariner.cfg "$FINAL_LINUX_CFG_PATH"
fi

# Update contents
sed -i "s/mariner_linux=.*$/mariner_linux=${FINAL_KERNEL_IMAGE}/" "$FINAL_LINUX_CFG_PATH"
sed -i "s/mariner_initrd=.*$/mariner_initrd=${FINAL_INITRD}/" "$FINAL_LINUX_CFG_PATH"

# Update mariner.cfg symlink so grub boots this configuration now
ln -sf linux-"$KERNEL_VERSION".cfg "$DEST_DIR"/mariner.cfg

exit 0
