#!/bin/bash
#
#
# Bootstrap the usb stick
#

if [ "${UID}" != "0" ]; then
	echo "This must be run as root.  Sorry."
	exit 1
fi

# Maybe derive the current root dynamically...
SRC_DEV=`df -h / | grep -v File | awk '{print $1}'`
echo The current root device is ${SRC_DEV}

# These should be parameterized via getopt
TARGET_DEV=/dev/sdb
TARGET_PARTITION=1
STICK_MOUNT=/mnt/stick

# This is an assumption that when we boot we only have a single
# boot device on sd* (our lowly usb stick)
STICK_BOOT_DEV=/dev/sda1

# Copy the source device raw to our stick...
echo Copying the source device to the usb stick...
/bin/dd if=${SRC_DEV} of=${TARGET_DEV}${TARGET_PARTITION}

# Apparently the device could still be active even after dd returns
echo Waiting 3 seconds for device to chill...
sleep 3

# Mount the stick 
echo Mounting the usb stick to ${STICK_MOUNT}
/bin/mount ${TARGET_DEV}${TARGET_PARTITION} ${STICK_MOUNT}

#grub-install --root-directory=${STICK_MOUNT} --recheck ${TARGET_DEV}
/usr/sbin/grub-install --root-directory=${STICK_MOUNT} ${TARGET_DEV}

# Now to fix up the configs...

# Huge assumption here that normal audiopint operation has boot 
# as sda1 and hd0,1 (sole scsi device)
# TODO: Make me better.
echo Doing drive/partition replacement in grub menu.lst...
cat /boot/grub/menu.lst | \
	sed -e "s|root=${SRC_DEV}|root=${STICK_BOOT_DEV}|" | \
	sed -e "s|hd.,.|hd0,0|" > ${STICK_MOUNT}/boot/grub/menu.lst

# Fix up fstab
echo Remapping drive/partition in /etc/fstab...
cat /etc/fstab | \
	grep -v '/media/usb' | \
	grep -v '/mnt/scratch' | \
	sed -e "s|${SRC_DEV}|${STICK_BOOT_DEV}|" > ${STICK_MOUNT}/etc/fstab

echo Unmounting usb stick ${STICK_MOUNT}
/bin/umount ${STICK_MOUNT}

echo Enjoy the audiopint and see audiopint.org
