#!/bin/bash -e

export LANG=C

echon() {
	printf "%s" "$@"
}
yesno()
{
	msg="$1"
	def="$2"
	while true ; do
	echon "$msg"
	read answer
	if [ "$answer" ] ; then
		case "$answer" in
		y|Y|yes|YES)
			return 0
			;;
		n|N|no|NO)
			return 1
			;;
		*)
			echo " "
			echo "Error: Invalid response, expected \"yes\" or \"no\"."
			continue
			;;
		esac
	else
		return $def
	fi
	done
}

usage()
{
echo "usage: $0 [OPTION]"
echo
echo "    -d target_device    specify target partition by device file name"
echo "    -u uuid(preferred)  specify UUID directly"
echo "    -v                  get current value"
echo "    -h                  print this message and exit"
echo
exit
}

exec_db()
{
tempfile=$(mktemp)
chmod +x "${tempfile}"
cat>${tempfile}<<EOT
#!/bin/bash -e
. /usr/share/debconf/confmodule
db_go
EOT
if ! ${VIEWMODE}; then
cat>>${tempfile}<<EOT
db_set grub-pc/install_devices "/dev/disk/by-uuid/${target_device_uuid}"
EOT
fi
cat>>${tempfile}<<EOT
db_get grub-pc/install_devices
db_stop
EOT
if ! ${VIEWMODE}; then
cat>>${tempfile}<<EOT
echo "Updated successfully."
EOT
fi
cat>>${tempfile}<<EOT
echo 2>&1 "grub-pc/install_devices: \${RET}"
rm "\${0}"
EOT
exec "${tempfile}"
}

test `id -u` -ne 0 && echo "Run as root." && exit 1
arg_target_device=;arg_uuid=;VIEWMODE=false
while getopts "d:u:vh" opt; do 
  case $opt in
    \?) OPT_ERROR=1; usage;;
    d) arg_target_device="$OPTARG";; # Optional argument: -d /dev/??
    u) arg_uuid="$OPTARG";;          # Optional argument: -u ?????
    v) VIEWMODE=true;;               # Optional argument: -v(Get current value)
    h) usage;;
  esac
done
${VIEWMODE} && exec_db
if test -n "${arg_target_device}" && test -n "${arg_uuid}"; then
echo "Warning: uuid has been given. target_device will be ignored."
fi
target_device=
if test -n "${arg_uuid}"; then
testline=$(echo "${arg_uuid}"|tr -d [:alnum:]|tr -d \-)
test -n "${testline}" && echo "Error, Invalid argument." && exit 1
target_device_uuid=${arg_uuid}
else
if test -n "${arg_target_device}"; then
if test ! -e "${arg_target_device}"; then
echo "Error, ${arg_target_device} does not exist." && exit 1
else
target_device=${arg_target_device}
fi
else
target_device=`mount|grep "on /boot "|cut -d" " -f1`
test -z "${target_device}" && target_device=`mount|grep "on / "|cut -d" " -f1`
fi
line=`blkid|grep "${target_device}:"`
line=${line#*UUID\=\"*}
line=${line%%\"*}
testline=$(echo "${line}"|tr -d [:alnum:]|tr -d \-)
test -n "${testline}" && echo "Error, Can't get UUID." && exit 1
target_device_uuid=${line}
fi
echo "target_device: ${target_device}"
echo "target_device_uuid: ${target_device_uuid}"
echo "The debconf database will be updated."
yesno "Proceed? yes or no [n] " 1 && exec_db
