#!/bin/sh
set -uxe
echo "libpam-mount is working" > expected

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

    fallocate -l 32M "/tmp/disk-l${id}.img"
    cryptsetup luksFormat --batch-mode --verbose --force-password --key-file=/home/alice/alice.key --type "${type}" "/tmp/disk-l${id}.img"
    cryptsetup open --type "${type}" --batch-mode --verbose --key-file=/home/alice/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}"
    echo "libpam-mount is working" > "${tdir}/testfile"
    umount "/dev/mapper/img-luks${id}"
    cryptsetup close "img-luks${id}"
}

checkluks()
{
    id=${1}
    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='/home/alice/alice.key' />" /etc/security/pam_mount.conf.xml

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

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

    # compare data on encrypted disk via local login shell
    # ensure su from root (needs no PW) does not re-ask for a pass (gets it from ~alice/alice.key anyway)
    sed -i -e 's/pam_mount.so\s*$/pam_mount.so disable_interactive/' /etc/pam.d/common-auth
    sed -i -e 's/pam_mount.so\s*$/pam_mount.so disable_interactive/' /etc/pam.d/common-session
    su --login --command "cat ~/img-luks${id}/testfile" alice > "luks${id}"
    sleep 5s
    cmp expected "luks${id}"

    # compare data on encrypted disk via ssh based login
    # shellcheck disable=SC2029
    ssh -o "StrictHostKeyChecking=no" -i test.key alice@localhost "cat ~/img-luks${id}/testfile" > "luks${id}"
    sleep 5s
    cmp expected "luks${id}"

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

# create user alice with PW alice
sudo useradd -m --password "$(openssl passwd -1 alice)" alice
# trivial passphrase
printf "alice" > ~alice/alice.key
# non interactive ssh login
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
# LUKS mountpoints
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
