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

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

BOOT=${VMT_DEVICE}/boot

if [ "$1" == "--help" ]; then
  echo "usage: $(basename $0) [--kernel ${VMT_KERNEL}] [--release ${VMT_RELEASE}]"
  exit 0
fi

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

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

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

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

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
 initrd /boot/vmtux64-${VMT_RELEASE}.gz
}
EOF

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

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

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

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

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

sudo grub-install --boot-directory=${BOOT} /dev/${bootdevice}

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

echo

echo "now it is a good time to reboot"

exit 0
