#!/bin/sh

SSHD_CONF=/etc/ssh/sshd_config
SSHD_PAM_CONF=/etc/pam.d/sshd
RUBLON_CONFIG=/etc/rublon.config
RUBLON_SHARE=/usr/local/share/rublon
RUBLON_PAM_MODULE_DIR=/usr/local/lib/security
RUBLON_PAM_MODULE=$RUBLON_PAM_MODULE_DIR/pam_rublon.so

# OpenPAM (unlike Linux-PAM) refuses to load a module it doesn't consider
# safely owned - confirmed live, 2026-08-31: "insecure ownership or
# permissions" / "Operation not permitted" in auth.log, PAM init failing
# outright for every login. The plain tarball this package installs from
# (see pack.cmake - CPack has no postinst hook of its own for the TGZ
# generator) preserves whatever UID built it, not root, since install_cmd
# extracts it as root via sudo (which restores archived ownership rather
# than reassigning it) - fix that up explicitly rather than relying on
# whatever the archive happened to record.
chown root:wheel "$RUBLON_PAM_MODULE_DIR" "$RUBLON_PAM_MODULE_DIR"/*.so
chmod 755 "$RUBLON_PAM_MODULE_DIR"
chmod 555 "$RUBLON_PAM_MODULE_DIR"/*.so

if [ ! -f "$RUBLON_CONFIG" ]
then
    cp -p "$RUBLON_SHARE/rublon.config.defaults" "$RUBLON_CONFIG"
    chown root:wheel "$RUBLON_CONFIG"
    chmod 600 "$RUBLON_CONFIG"
fi

# FreeBSD's base sshd_config has no `Include /etc/ssh/sshd_config.d/*.conf`
# directive (unlike Debian/Ubuntu's OpenSSH packaging, which is what this
# project's 01-rublon-ssh.conf drop-in relies on elsewhere) - there is
# nowhere to drop a snippet, so edit sshd_config directly instead. More
# importantly, the base image ships `UsePAM no` explicitly (confirmed
# live, 2026-08-31): with that set, sshd never consults PAM's auth stack
# at all, so pam_rublon.so would sit fully wired into /etc/pam.d/sshd
# below and still never run. sed -i '' (not bare -i) is FreeBSD/BSD sed's
# in-place syntax, not GNU sed's.
if grep -qE '^UsePAM[[:space:]]+no' "$SSHD_CONF"
then
    sed -i '' -E 's/^UsePAM[[:space:]]+no/UsePAM yes/' "$SSHD_CONF"
elif ! grep -qE '^UsePAM[[:space:]]+yes' "$SSHD_CONF"
then
    echo "UsePAM yes" >> "$SSHD_CONF"
fi
grep -qE '^PasswordAuthentication[[:space:]]+yes' "$SSHD_CONF" || echo "PasswordAuthentication yes" >> "$SSHD_CONF"

# Full path, not a bare module name - see PAM/ssh/lib/CMakeLists.txt's
# FreeBSD _destination comment: this package fully controls that
# directory, so referencing pam_rublon.so by its full path here sidesteps
# ever needing to know/verify OpenPAM's default module search path.
grep -qF "auth required $RUBLON_PAM_MODULE" "$SSHD_PAM_CONF" || echo "auth required $RUBLON_PAM_MODULE" >> "$SSHD_PAM_CONF"
grep -qF "account required $RUBLON_PAM_MODULE" "$SSHD_PAM_CONF" || echo "account required $RUBLON_PAM_MODULE" >> "$SSHD_PAM_CONF"

service sshd restart
