#!/bin/sh
#
#  This script sets up the ParaVM to use pygrub
#

prefix=$1

#
#  Source our common functions
#
if [ -e /usr/lib/xen-tools/common.sh ]; then
    . /usr/lib/xen-tools/common.sh
else
    . ./hooks/common.sh
fi

echo SCRIPT = $0
dir=`dirname "$0"`


logMessage Script $0 starting

#
# Install the xen kernel.  linux-image-xen is in ubuntu,
# linux-image-xen-{amd64,686} in debian.
#

installDebianPackage ${prefix} lsb-release

if [ "$(chroot ${prefix} lsb_release -is)" = "Ubuntu" ]; then
    if dpkg --compare-versions "$(chroot ${prefix} lsb_release -rs)" ge 8.10; then
        installDebianPackage ${prefix} linux-image-virtual
    else
        installDebianPackage ${prefix} linux-image-xen
    fi
else
    installDebianPackage ${prefix} linux-image-xen-amd64
    installDebianPackage ${prefix} linux-image-xen-686
fi

installDebianPackage ${prefix} grub

#
# Make the /boot/grub directory
#
mkdir -p ${prefix}/boot/grub

#
# Create stock menu.lst
#
chroot ${prefix} /usr/sbin/update-grub -y

#
# Patches to add xen kernels, use serial console, etc.
#
for patch in $dir/patches/*; do
    patch -l -d ${prefix} -p1 < $patch
done

#
# If this is a pv_ops kernel, then we need to make some more changes
# to make the console work right
#
if [ "$(chroot ${prefix} lsb_release -is)" = "Ubuntu" ] && \
    dpkg --compare-versions "$(chroot ${prefix} lsb_release -rs)" ge 8.10; then
    sed -i -e 's/xvc0/hvc0/' ${prefix}/etc/event.d/tty1
    sed -i -e 's/console=ttyS0[^ ]*/console=hvc0/' ${prefix}/boot/grub/menu.lst
fi

#
# Since pv_ops kernels force block device names to xvda, xvdb, etc,
# the default root value of root=/dev/hda won't actually help us.
#
# To work around that, find a UUID for the swap and root partitions
# and use that in the grub config (and also in /etc/fstab)
#
ROOT_DEV="$(perl -e 'print $ENV{"image-dev"}')"
SWAP_DEV="$(perl -e 'print $ENV{"swap-dev"}')"
ROOT_UUID="$(vol_id --uuid "$ROOT_DEV")"
SWAP_UUID="$(vol_id --uuid "$SWAP_DEV")"
sed -i -e "s#root=[^ ]*#root=UUID=$ROOT_UUID#" ${prefix}/boot/grub/menu.lst
sed -i -e "s#${ROOT_DEV}#${ROOT_UUID}#" ${prefix}/etc/fstab
sed -i -e "s#${SWAP_DEV}#${SWAP_UUID}#" ${prefix}/etc/fstab

#
# Regenerate automagic kernels list
#
chroot ${prefix} /usr/sbin/update-grub -y

#
# Log our finish
#
logMessage Script $0 finished

