#!/bin/sh

if [ "$(id -u)" != "0" ]; then
 echo "Error: You must be root to run this script!" >&2
 exit 1
fi

# dup uuid check
check_uuid () {
[ -n "$UUID_CHECK" ] && eval "case $1 in $UUID_CHECK) echo Error: Dup UUID found: $1 >&2; exit 2;; esac"
if [ -z "$UUID_CHECK" ]; then
 UUID_CHECK=$1
else
 UUID_CHECK="$UUID_CHECK|$1"
fi
}
unset UUID_CHECK
for p in $(tail -n +3 /proc/partitions|sed -r 's/.* (\S*)/\/dev\/\1/'|grep -v ^/dev/dm-;ls /dev/mapper/* 2>/dev/null); do
 unset ID_FS_USAGE ID_FS_TYPE ID_FS_UUID
 eval $(/lib/udev/vol_id $p 2>/dev/null|grep -e ^ID_FS_USAGE -e ^ID_FS_TYPE -e ^ID_FS_UUID)
 if [ -n "$ID_FS_UUID" ]; then
  [ "$ID_FS_USAGE" = "filesystem" ] && check_uuid $ID_FS_UUID
  [ "$ID_FS_USAGE" = "other" -a "$ID_FS_TYPE" = "swap" ] && check_uuid $ID_FS_UUID
 else
  echo "Warning: No UUID found for $p (${ID_FS_USAGE:-no-filesystem} ${ID_FS_TYPE:-no-type})" >&2
 fi
done

# write new root entry in menu.lst
unset DEV UUID
ROOT="$(grep "^# kopt" /boot/grub/menu.lst|sed -r "s/.*root=(\S+).*/\1/")"

case $ROOT in
 /dev/mapper/*) ;;
 /dev/disk/by-uuid/*) DEV=/dev/$(readlink $ROOT|sed s@../../@@)
                      UUID="UUID=${ROOT#/dev/disk/by-uuid/}"
                      ;;
 /dev/*) DEV=$ROOT
         UUID="UUID=$(/lib/udev/vol_id -u $ROOT)"
         ;;
 UUID=*) UUID=$ROOT
         DEV=/dev/$(readlink /dev/disk/by-uuid/${ROOT#UUID=}|sed s@../../@@)
         ;;
esac

if ! [ -x /usr/sbin/update-initramfs ]; then
 echo "Warning: initramfs-tools not installed!" >&2
 apt-get update
 apt-get install --allow-unauthenticated --yes initramfs-tools
fi

if ! [ -x /usr/sbin/update-initramfs ]; then
 echo "Error: update-initramfs not found!" >&2
 exit 1
fi

rm -f /etc/kernel-img.conf
cat << EOT > /etc/kernel-img.conf
# Kernel image management overrides
# See kernel-img.conf(5) for details
do_symlinks = yes
relative_links = yes
do_bootloader = no
do_bootfloppy = no
do_initrd = yes
link_in_boot = no
postinst_hook = update-grub
postrm_hook   = update-grub
EOT

[ -n "${UUID#UUID=}" ] && perl -pi -e 'next if /^\s*#+/ && ! /^\s*#(?!#+).*\Wkopt/; s|(?<!g)root=\S+|root='"$UUID"'|' /boot/grub/menu.lst
[ "$1" = "-d" -a -n "${DEV#/dev/}" ] && perl -pi -e 'next if /^\s*#+/ && ! /^\s*#(?!#+).*\Wkopt/; s|(?<!g)root=\S+|root='"$DEV"'|' /boot/grub/menu.lst

echo Old root: $ROOT
echo New root: $(grep "^# kopt" /boot/grub/menu.lst|sed -r "s/.*root=(\S+).*/\1/")

[ -d /var/lib/initramfs-tools ] && rm -f /var/lib/initramfs-tools/*
rm -f /boot/initrd*

for k in $(ls /boot/vmlinuz-* 2>/dev/null|sed 's|/boot/vmlinuz-||'); do 
 update-initramfs -c -k $k
done

update-grub
