#!/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
}

TEST_ID=pam_test

# 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"

if [ -z "$(id -u "$TEST_ID" 2> /dev/null || true)" ]; then
    useradd -s /bin/bash "$TEST_ID" || fail "add user fail"
fi
# and confirm that it makes a home directory
su -c /bin/true $TEST_ID || fail "su fail"
test -d "/home/$TEST_ID" || fail "pam_test home directory not made"

# confirm added options are preserved
# grep -i rounds /etc/pam.d/common-password && fail "rounds parameter already specified"
# sed -i -e 's/obscure yescrypt/obscure yescrypt rounds=3/' /etc/pam.d/common-password
#grep rounds /etc/pam.d/common-password || fail "sed did not update common password"

#( echo get libpam-runtime/profiles |debconf-communicate  |grep mkhomedir) || fail "mkhomedir not in enabled profiles"

# Confirm removing mkhomedir preserves  rounds parameter
#pam-auth-update --disable mkhomedir ||fail "pam-auth-update disable failed"
# not yet see #1039873
# ( echo get libpam-runtime/profiles |debconf-communicate |grep mkhomedir) && fail "mkhomedir still in profiles"
# grep mkhomedir /var/lib/pam/seen || fail "mkhomedir removed from seen after disable"
#grep  mkhomedir /etc/pam.d/common-session && fail "pam_mkhomedir not removed"
#grep rounds  /etc/pam.d/common-password || fail "rounds parameter not preserved"

userdel "$TEST_ID"
