#!/bin/sh
#
# VMTux.net
#
# vmt-kernel - make bootable partition on ${VMT_DEVICE}
#
. /etc/vmt/vmt-conf
. /etc/vmt/vmt-colors

PATH=/bin:/sbin

umask 022

if [ "$(id -u)" -eq 0 ]; then echo "${BRed}don't run as root${Reset}" ; exit 1; fi

BOOT=${VMT_DEVICE}/boot

blockname=$(basename $(readlink ${VMT_DEVICE}))

BOOTDEVICE="/dev/$(basename $(readlink -f /sys/class/block/${blockname}/..))"

latest=$(wget -O - --post-data "query=latest" ${VMT_MIRROR_URL}/upgradeinfo 2>/dev/null)
VMT_KERNEL=$(echo ${latest} | tr '\n' '\f' | sed -e 's/.*"kernel"[^"]*"\([^"]*\)".*/\1/')
VMT_RELEASE=$(echo ${latest} | tr '\n' '\f' | sed -e 's/.*"release"[^"]*"\([^"]*\)".*/\1/')  

if [ "$1" == "" ]; then
  echo "usage: $(basename $0) [--current]|[--kernel ${VMT_KERNEL}] [--release ${VMT_RELEASE}] [--boot-dir ${BOOT}] [--boot-device ${BOOTDEVICE}]"
  exit 0
fi

if [ "$1" == "--current" ]; then
  UPGRADE="yes"
  shift 1
fi

if [ "$1" == "--kernel" ]; then
  VMT_KERNEL="$2"
  shift 2
fi

if [ "$1" == "--release" ]; then
  VMT_RELEASE="$2"
  shift 2
fi

if [ "$1" == "--boot-dir" ]; then
  BOOT="$2"
  shift 2
fi

if [ "$1" == "--boot-device" ]; then
  BOOTDEVICE="$2"
  shift 2
fi

if [ ${UPGRADE} != "yes" ]; then
  exit 0
fi

read -p "Install vmlinuz64-${VMT_KERNEL} and vmtux64-${VMT_RELEASE} on ${BOOT} [Yn]: " yesno

if [ "$yesno" == "Y" ]; then

sudo mkdir -p ${BOOT}

echo -n "downloading vmlinuz64-${VMT_KERNEL} ..."
sudo rm -f ${BOOT}/vmlinuz64-${VMT_KERNEL}
sudo wget -q ${VMT_MIRROR_URL}/${VMT_RELEASE}/boot/VMTux-${VMT_KERNEL}/vmlinuz64-${VMT_KERNEL} -P ${BOOT}

if [ $? -ne 0 ]; then
  echo "error"
  exit 1
fi

echo "done"

echo -n "downloading vmtux64-${VMT_RELEASE}.gz ..."
sudo rm -f ${BOOT}/vmtux64-${VMT_RELEASE}.gz
sudo wget -q ${VMT_MIRROR_URL}/${VMT_RELEASE}/boot/VMTux-${VMT_KERNEL}/vmtux64-${VMT_RELEASE}.gz -P ${BOOT}

if [ $? -ne 0 ]; then
  echo "error"
  exit 1
fi

echo "done"

echo "creating/updating grub.cfg"
sudo mkdir -p ${BOOT}/grub
sudo dd status=none of=${BOOT}/grub/grub.cfg << EOF
# VMTux.net grub.cfg
set default=0
set timeout=0
hiddenmenu
menuentry "vmtux64-${VMT_KERNEL} `date`" {
 clear
 linux /boot/vmlinuz64-${VMT_KERNEL} loglevel=3 fbcon=map:0
 initrd /boot/vmtux64-${VMT_RELEASE}.gz
}
EOF

# end of kernel update
fi

read -p "grub-install on device ${BOOTDEVICE} [Yn]: " yesno

if [ "$yesno" != "Y" ]; then echo "exit" ; exit 0; fi

if [ ! -x /usr/local/sbin/grub-install ]; then
  vmt-install grub-2.12 >/dev/null
fi

sudo /usr/local/sbin/grub-install --target=i386-pc --install-modules="linux.mod" --locales="" --fonts="" --boot-directory=${BOOT} ${BOOTDEVICE}

if [ $? -ne 0 ]; then
  echo "error"
  exit 1
fi

echo

echo "now it is a good time to reboot"

exit 0
