#!/bin/sh

set -e

# Dummy user we create for our purposes
DUMMY=foo

if ! id $DUMMY >/dev/null 2>&1; then
	echo "Creating user $DUMMY"
	useradd $DUMMY
	mkdir -p /home/$DUMMY
	passwd $DUMMY
fi

apt-get -q -y install libpam-mount cryptsetup

# Enable pam_mount for login
if ! grep -q common-pammount /etc/pam.d/login; then
	echo '@include common-pammount' >> /etc/pam.d/login
fi

# Small loopback encrypted disk
dd bs=1k count=1024 if=/dev/zero of=/tmp/$DUMMY.bin
LOOP=`losetup -f`
losetup $LOOP /tmp/$DUMMY.bin
cryptsetup luksFormat $LOOP
cryptsetup luksOpen $LOOP $DUMMY
mke2fs /dev/mapper/$DUMMY
sleep 1
cryptsetup remove $DUMMY

# Update /etc/security/pam_mount.conf.xml with our definition
sed -i -e "\\|/home/$DUMMY|d" /etc/security/pam_mount.conf.xml
sed -i -e "/Volume definitions/ a<volume mountpoint=\"/home/$DUMMY\" path=\"$LOOP\" fstype=\"crypt\" options=\"nodev,nosuid,fsck\" />" /etc/security/pam_mount.conf.xml

# Log in and have fun!
echo "Logging in..."
login $DUMMY

