# pacman install script of plinius-security: lists pam_plinius_secstate.so at the end of the
# password stacks of /etc/pam.d/passwd and /etc/pam.d/chpasswd (backup files of the shadow
# package), so a new login password (the screen lock PIN) gets rated for GNOME Settings: passwd
# for changes in Settings, chpasswd for the first PIN the greeter sets. Removed with the package.
# Also puts the post-quantum key exchange first in GnuTLS's default priority (plinius-gnutls-pq,
# /etc/gnutls/config), and takes it out again on removal.

_pam_line='password	optional	pam_plinius_secstate.so'
_pam_files=(/etc/pam.d/passwd /etc/pam.d/chpasswd)

_add_pam_line() {
	local f
	for f in "${_pam_files[@]}"; do
		[[ -f $f ]] || continue
		grep -q 'pam_plinius_secstate\.so' "$f" && continue
		# Last: it rates only a password that the modules before it have set
		printf '%s\n' "$_pam_line" >> "$f"
	done
}

# Up to 0.1-13 the module left the modes to passwd's umask (077 from GNOME Settings): Settings,
# running as the user, could not read the ratings. Directories 0755, each rating 0640 for its user.
_fix_rating_modes() {
	local d=/var/lib/plinius-security f g
	[[ -d $d/lock ]] || return 0
	chmod 0755 "$d" "$d/lock"
	for f in "$d"/lock/*; do
		[[ -f $f && ! -L $f ]] || continue
		g=$(id -gn "${f##*/}" 2>/dev/null) || continue
		chown "root:$g" "$f" && chmod 0640 "$f"
	done
}

_gnutls_pq=/usr/lib/plinius-security/plinius-gnutls-pq

post_install() {
	_add_pam_line
	"$_gnutls_pq" add
}

post_upgrade() {
	_add_pam_line
	_fix_rating_modes
	"$_gnutls_pq" add
}

pre_remove() {
	local f
	"$_gnutls_pq" remove || true
	for f in "${_pam_files[@]}"; do
		sed -i '/pam_plinius_secstate\.so/d' "$f" 2>/dev/null || true
	done
}
