_AUTOMOUNTS="home.automount home-bl-basement.automount"

# Validate before reloading: on a bad config sshd would fail to come back,
# and on a remote box that is a lockout.
_reload_sshd() {
    if sshd -t 2>/dev/null; then
        systemctl try-reload-or-restart sshd.service 2>/dev/null || true
    else
        echo "==> WARNING: 'sshd -t' failed; NOT reloading sshd. Fix this first:"
        sshd -t 2>&1 | sed 's/^/    /'
    fi
}

_common() {
    systemctl --global enable uhhm-session-init.service 2>/dev/null || true
    systemd-tmpfiles --create /usr/lib/tmpfiles.d/uhhm.conf 2>/dev/null || true
    pacman-key --populate uhhm >/dev/null 2>&1 || true
    _reload_sshd
}

post_install() {
    _common
    cat <<'EOF2'
==> uhhm-corp installed. Enrol this device with:
      sudo uhhm-corp-setup                  # VPN + kanidm login
      sudo uhhm-corp-setup --with-nfs-home  # ...plus /home from ergo (shadows local /home)
      uhhm-ssh-enroll                       # per-user: give THIS machine its own SSH key in kanidm
==> UID note: kanidm accounts must carry the same uid/gid as on ergo's
    NFS export (e.g. `kanidm person posix set --gidnumber 1000 bl`).
EOF2
}

post_upgrade() {
    # renamed from uhhm-gpg-nfs-locks in 0.2.3
    systemctl --global disable uhhm-gpg-nfs-locks.service 2>/dev/null || true
    # 0.2.9: automounts moved from multi-user.target to remote-fs.target;
    # re-link the ones already enabled so the old symlink doesn't linger.
    if [ "$(vercmp "$2" 0.2.9)" -lt 0 ]; then
        for u in $_AUTOMOUNTS; do
            systemctl -q is-enabled "$u" 2>/dev/null && systemctl reenable "$u" 2>/dev/null
        done
        echo "==> 0.2.9: /home is now a hard NFS mount (was soft); takes effect on remount/reboot."
    fi
    _common
}

pre_remove() {
    systemctl disable $_AUTOMOUNTS 2>/dev/null || true
    systemctl --global disable uhhm-session-init.service 2>/dev/null || true
    if grep -q pam_kanidm /etc/pam.d/system-auth 2>/dev/null; then
        cat <<'EOF2'
==> NOTE: /etc/pam.d/system-auth and /etc/nsswitch.conf still reference kanidm.
    Run `sudo uhhm-corp-setup --undo` BEFORE removing uhhm-corp, or remove the
    pam_kanidm lines and the `kanidm` NSS entries by hand.
EOF2
    fi
}
