#!/bin/bash

#Functions
# boot_download Function

# Downloading all in SLX_BASE_PATH to  /boot  Example: Ubuntu_1404_x64
# wget -N,  update if the file has been changed
boot_download () {
        echo "Downloading $SLX_BASE_PATH ................."
        wget -P /boot -N -r --tries=3 --timeout=5 --quiet -nH -l1 --no-parent --reject="index.html*" --reject="$SLX_BASE_PATH.*" $SLXSRV/$SLX_BASE_PATH #<---- ok =), but try with -nc too
        RET=$?
        [ $RET != 0 ] && { echo "Error - downloading 'http://$SLXSRV/$SLX_BASE_PATH' via wget failed."; exit 1; } || { echo "Successfully downloaded  'http://$SLXSRV/$SLX_BASE_PATH' via wget."; return 0; }

}


# get_cmdline Function, get all informations necessary from the system like boot_partition, GPT or msdos, Web server address. 

get_cmdline () {
# Getting informations from cmdline

CMDLINE='/proc/cmdline'

read KCL < "$CMDLINE"
for opts in ${KCL}; do
        case "${opts}" in
                slxbase=*)      # BASE_PATH Example Ubuntu_1404_x64
                        SLX_BASE_PATH=${opts#slxbase=} ;;
                slxsrv=*)
                        #SLX IP server info
                        SLXSRV=${opts#slxsrv=} ;;
                BOOT_IMAGE=*)
                        BOOT_IMAGE=${opts} ;;
                initrd=*)
                        initrd=${opts} ;;
        esac
done
KCL=$(echo "$KCL" | sed "s|SLX_BASE_PATH|$SLX_BASE_PATH|g;s|$BOOT_IMAGE||g;s|$initrd||g")

#Find disk of /boot
BOOT_DISK=$(df | grep /boot | awk '{print $1}' | tr -d '[0-9]' | cut -c 6-)
BOOT_PART=$(df | grep /boot | awk '{print $1}' | tr -dc '[0-9]')
[ -z "$BOOT_DISK" ] && { echo "BOOT DISK could not be found, exiting.";  exit 1; }

#Check if disk is msdos or GPT
if sgdisk /dev/$BOOT_DISK | grep -qs 'invalid GPT'; then
        BOOT_TYPE='msdos'
else
        BOOT_TYPE='gpt'
fi

# In same case a simple /boot is necessary, but hdX form runs always.

       case $BOOT_DISK in
                sda) GRUB_DISK=hd0 ;;
                sdb) GRUB_DISK=hd1 ;;
                sdc) GRUB_DISK=hd2 ;;
                sdd) GRUB_DISK=hd3 ;;
                sde) GRUB_DISK=hd4 ;;
                sdf) GRUB_DISK=hd5 ;;
                *) echo "GRUB_DISK was not found"
                exit 1 ;;
        esac
#

}

# install_grub Function # Only for first time install #

install_grub () {
        

	grub-install --boot-directory=/boot /dev/$BOOT_DISK
#       update-grub-gfxpayload

        RET=$?
        [ $RET != 0 ] && { echo "Could not install GRUB";  exit 1; } ||  echo "GRUB successfully installed"

        # copy grub.cfg, only if grub-install was successfully installed.
        [ -e /opt/openslx/hdd-boot/grub.cfg ] && cp -r /opt/openslx/hdd-boot/grub.cfg /boot/grub/

}

# make_menu Function # Add a menuentry for boot to grub menu. 

make_menu () {
cat <<EOF >> /boot/grub/grub.cfg
#########################
        menuentry '$SLX_BASE_PATH' {
        linux ($GRUB_DISK,${BOOT_TYPE}$BOOT_PART)/$SLX_BASE_PATH/kernel  hdd_boot=${BOOT_DISK}$BOOT_PART $KCL
        initrd ($GRUB_DISK,${BOOT_TYPE}$BOOT_PART)/$SLX_BASE_PATH/initramfs-stage31
}
#########################
EOF
#Remove vga=default because it causes error on kernel boot.
sed -i 's/vga=current//g' /boot/grub/grub.cfg
echo "Add menuentry for $SLX_BASE_PATH"
}

# End Functions



# Letś start the program

#[ ! -d /boot ] && {  echo "/boot Not Found"; exit 1; }
[ ! -d /boot ] && {  mkdir /boot; mount /dev/sda1 /boot; }

get_cmdline

# Verify for first time installation.
if [ ! -d /boot/grub ]; then

#First time, so install grub
				mkdir /boot/grub	
				install_grub
fi

if ! grep -qs "menuentry '$SLX_BASE_PATH'" /boot/grub/grub.cfg; then
# Need add a menuentry to make_menu

				boot_download
				make_menu												 
				
else
# if SLX_BASE_PATH already exists, just update. Does not make the menu again.
				
				boot_download


fi

echo  "--------- NO ERRORS FOUND -----------"

true














#FUTURE for VM
#####################################################################################

# ##Scan vm-store dir for vmware image xmls and copy

#if [ -d /cache/export/dnbd3 -a -d /mnt/vmstore ]; then
#	[ ! -d /boot/vmstore ] && mkdir /boot/vmstore
#	for FILE in $(find /cache/export/dnbd3 -iname "*.vmdk*" ! -iname "*map"); do
#		[ -e "${FILE}.map" ] && continue
#		image_name=$(echo $(basename "$FILE") | cut -d "." -f1)
#		cd /mnt/vmstore
#		for XML in $(grep -rIl --include "*.xml" "$image_name" .); do
#			xmldir=$(dirname $XML)
#			mkdir -p /boot/vmstore/${xmldir}
#			cp $XML /boot/vmstore/${xmldir}/
#		done
#		cd - >/dev/null
#	done
#fi
#
# #Bind mount available vmstore in /boot to /mnt/vmstore if not already present
#if ! grep -qs '/mnt/vmstore' /proc/mounts; then
#	[ ! -d /mnt/vmstore ] && mkdir -p /mnt/vmstore
#	[ -d /boot/vmstore ] && mount --bind /boot/vmstore /mnt/vmstore
#fi

######################################################################################

