#!/bin/bash

# Copyright 2023, Sam Hartman
# This code may be redistributed under the same terms as Linux Pam
# itself, or at your pution, under the GNU General Public License,
# version 3. 

set -ex

fail() {
    echo "$1" 2>&1
    echo "------------------ dump log -------------------"
    journalctl --no-pager
    exit 1
}

# Confirm enabling pam_mkhomedir updates common-session
grep mkhomedir /etc/pam.d/* && fail "pam_mkhomedir already enabled"
pam-auth-update --enable mkhomedir || fail "pam-auth-update enable failed"
grep mkhomedir /etc/pam.d/common-session || fail "pam_mkhomedir was not enabled"
echo 'session    required     pam_namespace.so' >> /etc/pam.d/common-session
mkdir -m 000 /tmp-inst
echo '/tmp     /tmp-inst/            user 	 root' >> '/etc/security/namespace.conf'

if [ -z "$(id -u alice 2> /dev/null || true)" ]; then
    useradd -s /bin/bash alice || fail "add user fail"
fi
if [ -z "$(id -u bob 2> /dev/null || true)" ]; then
    useradd -s /bin/bash bob || fail "add user fail"
fi

# and confirm that it makes a home directory
su -c /bin/true alice || fail "su fail"
su -c /bin/true bob || fail "su fail"
test -d "/home/alice" || fail "pam_test home directory not made"
test -d "/home/bob" || fail "pam_test home directory not made"

# and confirm that it makes a home directory
su -c 'install -m 666 /usr/share/common-licenses/GPL /tmp/secret' alice || fail "su fail"
su -c 'head /tmp/secret' alice || fail "su fail"
su -c 'head /tmp/secret' bob 2>&1 && fail 'found secret'

userdel bob
userdel alice
echo '' > '/etc/security/namespace.conf'
sed -i '/pam_namespace.so/d' /etc/pam.d/common-session
rm -rf /tmp-inst
