#!/bin/sh


if [ "$#" -ne "2" ] && [ "$#" -ne "3" ] ; then
    echo "make-me-bootable <fname> <drive> [noaction]"
    exit 1
fi

drivetouse=$2
boot_drv=""
boot_part=""
root_drv=""
root_part=""
if [ ! "$LOGFILE" ]; then
	LOGFILE="/tmp/mondorestore2.log"
fi
dummy="$3"

activepart=`mr_parted2fdisk -l $drivetouse 2>/dev/null | tr -s '\t' ' ' | grep "$drivetouse" | grep '*' | cut -d' ' -f1`

for i in `cat $1 | tr -s '\t' ' ' | cut -d' ' -f1 | grep -vE "/dev/fd|none|#"` ; do
	# Warning wrong if LVM !
    drive=`echo $i | sed -e 's/[0-9]*$//' -e 's/\([0-9]\)p$/\1/'`
	if [ "$drivetouse" = "$drive" ]; then
		# We can continue as this is the drive we ned to work on
    	partno=`echo $i | sed -e 's/^.*[^0-9]\([0-9]*\)$/\1/'`
    	mountpt=`grep "$i " $1 | tr -s '\t' ' ' | cut -d' ' -f2`

        if [ "$mountpt" = "/" ] ; then
            root_drv=$drive
		    root_part=$partno
        elif [ "$mountpt" = "/boot" ] ; then
            boot_drv=$drive
            boot_part=$partno
        fi
    fi
done

if [ "$boot_drv" ] ; then
    drive=$boot_drv
    partno=$boot_part
elif [ "$root_drv" ] ; then
    drive=$root_drv
    partno=$root_part
else
    driveline=`grep -E '[ 	]/boot[ 	]' $1`
    [ ! "$driveline" ] && driveline=`grep -E '[ 	]/[ 	]' $1`
    partno=`echo "$driveline" | cut -d' ' -f1 | awk -F "[a-z]" '{print $NF;}'`
#    echo "driveline=$driveline --> partno=$partno"
fi

if [ "$drive" ] ; then
    if [ "$partno" = "0" ] || [ ! "$partno" ] ; then
	   	partno="1"
	fi
	cmd=""
	for p in "$activepart"; do
		# First desactivate active partitions (coming from previous usage)
		cmd="${cmd}a\n$p\n"
    	if [ "$dummy" != "" ] ; then
			echo "Will desactivate $p on $drive" >> $LOGFILE
		fi
	done
	# Then activate the one which should
    if [ "$dummy" != "" ] ; then
		echo "Would activate $partno on $drive" >> $LOGFILE
	else
		echo -en "${cmd}a\n$partno\np\nw\n" | mr_parted2fdisk $drive >> $LOGFILE 2>> $LOGFILE
	fi
fi
exit 0
