#!/bin/sh
# Adds pam_c8wallet to the PAM files that need it:
#   sddm    auth (after the others: pam_unix has checked the password),
#           session (after the others: pam_systemd has made the runtime
#           dir) and password: the wallet opens with the login password
#   passwd  password: a changed password changes a running wallet's too
# Every line is optional, so it can't stop a login or a password change.
#
# Tumbleweed ships these in /usr/lib/pam.d; one in /etc/pam.d replaces
# it, so we start from that copy (later changes to the shipped one then
# don't reach it). Run again, it only updates the module path. Packages
# (DESTDIR) are left alone: /etc/pam.d is the admin's.
set -eu
module=$1
if [ -n "${DESTDIR:-}" ]; then
	echo "pam_c8wallet: not touching /etc/pam.d in a DESTDIR install; add" \
		"\"auth/session/password optional $module\" to sddm and" \
		"\"password optional $module\" to passwd"
	exit 0
fi

add() { # service, the types it gets
	service=$1
	shift
	conf=/etc/pam.d/$service
	if [ ! -e "$conf" ]; then
		for shipped in /usr/lib/pam.d/$service /usr/etc/pam.d/$service; do
			if [ -e "$shipped" ]; then
				cp "$shipped" "$conf"
				break
			fi
		done
	fi
	if [ ! -e "$conf" ]; then
		echo "pam_c8wallet: no PAM file for $service; skipped"
		return
	fi
	tmp=$(mktemp "$conf.XXXXXX")
	grep -v 'pam_c8wallet' "$conf" | awk -v m="$module" -v types="$*" '
		BEGIN { n = split(types, want, " ") }
		{ line[NR] = $0; for (i = 1; i <= n; i++) if ($1 == want[i]) last[want[i]] = NR }
		END {
			for (l = 1; l <= NR; l++) {
				print line[l]
				for (i = 1; i <= n; i++)
					if (last[want[i]] == l)
						printf "%-8s optional       %s\n", want[i], m
			}
		}' > "$tmp"
	chmod 644 "$tmp"
	mv "$tmp" "$conf"
	echo "pam_c8wallet: $conf ($*)"
}
add sddm auth session password
add passwd password
