#!/bin/sh
#
# $Id: label-partitions-as-necessary 1755 2007-10-31 00:11:44Z bruno $
#
############################################


read_partition_line() {
    local label mountpt command format

	label=`echo "$1" | awk '{print $1}' | cut -d'=' -f2`
	format=`echo "$1" | awk '{print $3}'`
	mountpt=`awk '{print $1,$5}' $mountlist | grep " $label$" | awk '{print $1}'`

	if [ "`echo "$1" | grep -E 'LABEL='`" != "" ] ; then
		opttun="-L"
	elif [ "`echo "$1" | grep -E 'UUID='`" != "" ] ; then
		opttun="-U"
	else
		# Nothing to do
		return
	fi

	if [ ! "$mountpt" ] ; then
		LogIt "Not labeling anything as ($label) because ($mountpt) is not a mountpoint"
	elif [ ! "$label" ] ; then
		LogIt "Not labeling ($mountpt) as anything because ($label) is not a label"
	else
		if [ "$format" = "ext2" ] || [ "$format" = "ext3" ] ; then
			command="tune2fs $opttun $label $mountpt"
			LogIt "Running $command"
			$command
		elif [ "$format" = "swap" ] ; then
			if [ "$opttun" = "-U" ]; then
				echo "Unable yet to identify swap with UUID"
				echo "You'll have to modify your /etc/fstab after reboot"
				echo "Replace the UUID found on the swap line by the one"
				echo "given by the command vol_id -u $mountpt"
				echo "And ask Ubuntu guys to deliver a mswap command with"
				echo "a -U option to update the UUID to what we want !!!"

				sleep 5
			else
				command="mkswap $opttun $label $mountpt"
				LogIt "Running $command"
				$command
			fi
		else
			LogIt "I am NOT going to run tune2fs: the partition is format '$format', which doesn't like tune2fs anyway"
		fi
	fi
}


# ---------------------------------------------

LogIt "Identifying your drives with tune2fs"
if [ "$#" -ne "1" ] ; then
    LogIt "label-partitions-as-necessary /tmp/mountlist.txt < /tmp/fstab.new" 1
    exit 1
fi
mountlist=$1
noof_blank_lines=0
read line
while [ "$line" != "" ] && [ "$noof_blank_lines" -le "5" ] ; do
    if [ "$line" = "" ] ; then
		noof_blank_lines=$(($noof_blank_lines+1))
    else
		noof_blank_lines=0
		read_partition_line "$line"
    fi
    read line
done
LogIt "Labeling complete."
exit 0
