#!/bin/bash

verbose(){
	[ -n "$verbose" ] && echo $@
}

show_help(){
cat <<'EOF'
    fixmbr - restore MBR erased by Microsoft Windows (TM)

    Usage: fixmbr [options]

    Options:
        -e, --edit                  start editor for manusl editing lilo.conf;
	-v, --verbose               be more verbose;
	-h, --help                  show this text and exit.

    Set $EDITOR variable to change an editor for manual lilo.conf editing

    Report bugs to http://bugzilla.altlinux.ru/

EOF
exit
}

[ -z "$EDITOR" ] && EDITOR=/usr/bin/mcedit 

TEMP=`getopt -n fixmbr -o v,h,e -l verbose,help,edit -- "$@"` || show_help
eval set "--" $TEMP

while :; do
	case "$1" in
                -v|--verbose) verbose=-v
		;;
                -h|--help) show_help
		;;
		-e|--edit) edit=1
		;;
		--) shift; break;
		;;
	esac
	shift
done

verbose "Mounting partitions"
mount-system

for system in /mnt/system* ; do
	if  grep -q 'boot="/dev/disk/by-id"' $system/etc/lilo.conf || grep -q 'boot="/dev/[^0-9]*"' $system/etc/lilo.conf ; then
		device=$(grep 'boot="/dev/"' $system/etc/lilo.conf |
		sed 's/.*"\/dev\/\(.*\)"/\1/')
		seen=$(eval "echo \$$device")
		if [ -z "$seen" ] ; then
			if [ -n "$edit" ] ; then
				verbose "Starting editor..."
				$EDITOR $system/etc/lilo.conf
			fi
			verbose running lilo for $system
			if chroot $system lilo ; then
				eval "$device=done"
				ok=yes
			fi
		fi
	fi
done

if [ -z "$ok" ] ; then
	verbose "Automatic fixing failed, starting editor..."
	$EDITOR $system/etc/lilo.conf
	verbose running lilo for $system
	chroot $system lilo
fi
