#!/bin/sh

# This hook will add an entry to crypttab and to fstab so the default 
# boot system of debian will mount an encrypted partition as /home.
#
# 1 - Create a partition for the live image in the USB key. One where the live
# image will fit.
#
# 2 - Create the luks partition with an ext2 filesystem in it
# and copy /home/* into it (an existing encrypted /home on harddisk 
# can be used instead). 
#
# 3 - Find what is the uuid of the encrypted partition:
#
#       ls -l /dev/disks/by-uuid
# 
# 4 - Now paste the uuid into this hook and (re)build your live cd.
#
# 5 - Use unetbootin or copy the live image manually to the first partition. 
#
# 6 - Boot with "lukshome" boot option to enable the hook. 
#
# NOTE: You can't use "persistent" and "lukshome" at the same time! If you do,
# lukshome hook will be *skipped*, but any persistent partition or file
# will be mounted.
#
# TODO/FIXME: add a boot option to select partition from boot options,
# like "lukshome_uuid="500a7752-385b-45e1-8119-dd35ce3544fb" and/or
# lukshome_part=/dev/sdb4 (this last one not hardware independent).


# scripts/live-bottom/13usb_luks_home, right after 12fstab
echo "I: creating /usr/share/initramfs-tools/scripts/live-bottom/13usb_luks_home"

cat > /usr/share/initramfs-tools/scripts/live-bottom/13usb_luks_home << 'EOF'
#!/bin/sh

#set -e

# initramfs-tools header

PREREQ=""

prereqs()
{
	echo "${PREREQ}"
}

case "${1}" in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /scripts/live-functions

# live-initramfs hook to add the luks home partition to crypttab and fstab

log_begin_msg "Executing usb-luks-home"

# get boot option lukshome without persistent- adapted from live-helpers
for ARGUMENT in $(cat /proc/cmdline)
do
	case "${ARGUMENT}" in
		persistent*)
			# FIXME: should we panic instead?
			echo
			echo "You should not use persistent and lukshome at the same time."
			echo "Skipping lukshome."
			log_end_msg
			exit 0
			;;
		lukshome)
			LUKSHOME=1
			;;
	esac
done

# if no boot option, exit
if [ -z "${LUKSHOME}" ]
then
	log_end_msg
	exit 0
fi

LUKSHOME_UUID="500a7752-385b-45e1-8119-dd35ce3544fb"

echo
echo "Adding ${LUKSHOME_UUID} to /etc/crypttab and setting it as /home in /etc/fstab."

# update cryptab
echo "home /dev/disk/by-uuid/${LUKSHOME_UUID} none luks,check,timeout" >> /root/etc/crypttab

# update fstab
echo "/dev/mapper/home /home ext2 defaults,noatime 0 0" >> /root/etc/fstab

log_end_msg

EOF

chmod 0755 /usr/share/initramfs-tools/scripts/live-bottom/13usb_luks_home


# if you already have the update-initramfs.sh hook, you can remove this.
echo "I: update-initramfs to include 13usb_luks_home."

for KERNEL in /boot/vmlinuz-*
do
	VERSION="$(basename ${KERNEL} | sed -e 's|vmlinuz-||')"

	update-initramfs -k ${VERSION} -t -u
done
