#!/bin/sh
# Vector Linux LILO
#
# Author: Eko M. Budi for Vector Linux
# License : GNU GPL
#

BACKTITLE="Vector Linux Repair LILO"
vdir=$(dirname $0)
. $vdir/setup-functions

LOG="/tmp/setup-lilo.log"

# Mount a device and look if there is a /sbin/vliloconf
# $1 = the device
build_rootdisk_menu() {
    # umount for sure
    umount $ROOT_MNT 2>/dev/null
    ii=0
    while read DEV; do
        if (mount $DEV $ROOT_MNT -t auto )> /dev/null 2>&1; then
	    if [ -x $ROOT_MNT/sbin/config-lilo ]; then
    		echo "'$DEV' 'Reinstall LILO from $DEV' \\"
		ii=`expr $ii '+' 1`
	    fi
	    sumount $ROOT_MNT > /dev/null 2>/dev/null
	fi
    done
    [ $ii = 0 ] && return 1
    return 0
}

menu_lilo()
{
    infobox "Finding Vector Linux installation ..."
    
    TITLE="REINSTALL LILO"
    DIMENSION="16 60 4"
    TEXT="\n
This menu allows you to reinstall LILO (Linux Loader) quickly.
The following menu shows the harddisk partition(s) that
contains Vector Linux.\n
Which one do you want as the main Linux?"

    probepart | grep -e "83 *Linux" | cut -f 1 -d ' ' > /tmp/hdlist

    echo '$DCMD --backtitle "$BACKTITLE" --title "$TITLE" \' > $fmenu
    echo '--menu "$TEXT" $DIMENSION \' >> $fmenu
    build_rootdisk_menu < /tmp/hdlist >> $fmenu
    if [ $? != 0 ]; then
	msgbox "Sorry, cannot find Vector Linux installation" "REINSTALL LILO"
	clean_exit 0    
    fi
    echo '2> $freply' >> $fmenu

    . $fmenu
    
    status=$?
    [ $status != 0 ] && return 3

    ROOT_DEV=$(cat $freply)
    if (mount $ROOT_DEV $ROOT_MNT -t auto )> $LOG 2>&1; then
	infobox "Preparing LILO configuration on $ROOT_DEV ..."
	# mount /proc & /dev first
	mkdir -p $ROOT_MNT/proc
	if (mount -t proc none $ROOT_MNT/proc) > $LOG 2>&1; then
	    mkdir -p $ROOT_MNT/sys
    	    if grep -w sysfs /proc/filesystems 1> /dev/null 2>&1 ; then
		mount -t sysfs none $ROOT_MNT/sys
	    fi
	    # no need to mount /dev, we are not using udev
	    # mkdir -p $ROOT_MNT/dev
	    # mount -o bind /dev $ROOT_MNT/dev > $LOG 2>&1
	    chroot $ROOT_MNT /sbin/config-lilo / $ROOT_DEV
	    status=$?
	    #umount $ROOT_MNT/dev
	    umount $ROOT_MNT/sys  > $LOG 2>&1
	    umount $ROOT_MNT/proc > $LOG 2>&1
	    sumount $ROOT_MNT > $LOG 2>&1
	    ## if cannot umount, must reboot
	    if [ $? != 0 ]; then
	       if [ $status = 0 ]; then
	         TEXT="LILO has been reinstalled. Reboot now"
	       else
	         TEXT="ERROR, cannot reinstall LILO. Reboot now"
	       fi
		msgbox "$TEXT" "REBOOT"
	        reboot_exit
	    fi
	    if [ $status = 0 ]; then
		TEXT="\nLILO has been reinstalled.\nDo you want to reboot the system now ?"
		$DCMD --backtitle "$BACKTITLE"  --title "LILO REINSTALLED" --yesno "$TEXT" 10 54 2> /dev/null
		status=$?
		[ $status != 0 ] && return 0
	        reboot_exit
	    fi
	else
	    sumount $ROOT_MNT
	fi
    fi
    msgbox "Sorry, reinstalling LILO has failed" "ERROR"
    clean_exit 0    
}

##############
# main menu, ouch only 1
menu_lilo

