#!/bin/sh
# Apply the ISM minimum passphrase length for a system's applicability, on a
# Debian 13 (trixie) host.
#
# Usage: apply-minlen.sh <NC|OS|P|S|TS>
#
# The argument is the system's ISM applicability code, exactly as the catalogue
# uses it. NC, OS and P share one minimum (15); S is 17 and TS is 20.
#
# Requires debian-13-pwquality-base: pam_pwquality must already be installed and in
# the password stack, or nothing here is enforced. Pair it with
# debian-13-pwquality-no-complexity as well, or character-class credits can let a
# shorter password satisfy the minimum.
#
# Idempotent: safe to re-run.

set -eu

APPLICABILITY=$(printf '%s' "${1:-}" | tr '[:lower:]' '[:upper:]')
case "$APPLICABILITY" in
	NC|OS|P) TIER=nc-os-p ;;
	S)       TIER=s ;;
	TS)      TIER=ts ;;
	*)       echo "usage: $0 <NC|OS|P|S|TS>" >&2; exit 2 ;;
esac

[ "$(id -u)" -eq 0 ] || { echo "error: must run as root" >&2; exit 1; }

BASE_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
DROPIN="50-ism-minlen-${TIER}.conf"
[ -f "$BASE_DIR/config/pwquality.conf.d/$DROPIN" ] || { echo "error: missing $DROPIN" >&2; exit 1; }

grep -qE '^[^#]*pam_pwquality\.so' /etc/pam.d/common-password || {
	echo "error: requires debian-13-pwquality-base: pam_pwquality.so is not in /etc/pam.d/common-password," >&2
	echo "       so nothing this component configures would be enforced." >&2
	exit 1
}

echo "==> installing $DROPIN for applicability $APPLICABILITY"
install -d -m 0755 /etc/security/pwquality.conf.d
install -m 0644 "$BASE_DIR/config/pwquality.conf.d/$DROPIN" "/etc/security/pwquality.conf.d/$DROPIN"

# Exactly one minimum may be live: conf.d is read in ASCII sort order and the last
# minlen silently wins.
for f in /etc/security/pwquality.conf.d/50-ism-minlen-*.conf; do
	[ "$f" = "/etc/security/pwquality.conf.d/$DROPIN" ] || rm -f "$f"
done

echo "==> applied. Verify with: scripts/verify-minlen.sh"
