#!/bin/bash
set -uxe
mkdir /etc/pam_mount_keys/
echo -n alice > /etc/pam_mount_keys/alice.key
echo "libpam-mount is working" > testfile

createluks()
{
    local id=${1}
    local type=${2}
    local tdir=$(mktemp --directory)

    fallocate -l 100M "/tmp/disk-l${id}.img"
    cryptsetup luksFormat --batch-mode --verbose --force-password --key-file=/etc/pam_mount_keys/alice.key --type "${type}" "/tmp/disk-l${id}.img"
    cryptsetup open --type "${type}" --batch-mode --verbose --key-file=/etc/pam_mount_keys/alice.key "/tmp/disk-l${id}.img" "img-luks${id}"
    mkfs.ext4 -L "IMG-LUKS${id}" "/dev/mapper/img-luks${id}"
    mount "/dev/mapper/img-luks${id}" "${tdir}"
    cp testfile "${tdir}"
    umount "/dev/mapper/img-luks${id}"
    cryptsetup close "img-luks${id}"
}

checkluks()
{
    local id=${1}
    local bckp=$(mktemp)

    # backup and modify configuration
    cp /etc/security/pam_mount.conf.xml "${bckp}"
    sed -i -e 's/debug enable="0"/debug enable="1"/' /etc/security/pam_mount.conf.xml
    sed -i -e "/<!-- Volume definitions -->/a<volume user='alice' path='/tmp/disk-l${id}.img' mountpoint='~/img-luks${id}' fstype='crypt' fskeycipher='none' fskeyhash='md5' fskeypath='/etc/pam_mount_keys/alice.key' />" /etc/security/pam_mount.conf.xml

    # smoke tests the mount and if not working print debug from journal
    ssh -o "StrictHostKeyChecking=no" -i test.key alice@localhost "ls -laF ~/img-luks${id}/testfile" || journalctl -xe -u ssh --no-pager

    # make sure we are using an actual mount
    ssh -o "StrictHostKeyChecking=no" -i test.key alice@localhost "mount" | grep img-luks${id}

    # compare data on encrypted disk
    ssh -o "StrictHostKeyChecking=no" -i test.key alice@localhost "cat ~/img-luks${id}/testfile" > "luks${id}"
    cmp testfile "luks${id}"

    # restore configuration
    cp "${bckp}" /etc/security/pam_mount.conf.xml
}

# create user alice with PW alice
sudo useradd -G users -m --password "$(openssl passwd -1 alice)" -s /bin/bash alice
ssh-keygen -t rsa -N "" -f test.key
mkdir -p ~alice/.ssh
chown alice:alice ~alice/.ssh
cp test.key.pub ~alice/.ssh/authorized_keys
mkdir -p /home/alice/img-luks1 /home/alice/img-luks2
chown alice:alice ~alice/.ssh/authorized_keys /home/alice/img-luks1 /home/alice/img-luks2

# create LUKS devices with known content
createluks 1 luks
createluks 2 luks2

checkluks 1
checkluks 2
