#!/bin/sh
set -eu
case "$1" in
  configure)
    if ! getent passwd mission-core-node >/dev/null; then
      adduser --system --group --home /var/lib/mission-core-node --no-create-home --disabled-login mission-core-node
    fi
    mc_node_ssh_snippet=/etc/ssh/sshd_config.d/60-mission-core-node.conf
    mc_node_ssh_template=/usr/share/mission-core-node/60-mission-core-node.conf
    if [ -L "$mc_node_ssh_snippet" ] || { [ -e "$mc_node_ssh_snippet" ] && ! cmp -s "$mc_node_ssh_template" "$mc_node_ssh_snippet"; }; then
      echo "Mission Core Node: existing custom SSH snippet preserved; configuration conflict." >&2
      exit 1
    fi
    install -D -m 0644 "$mc_node_ssh_template" "$mc_node_ssh_snippet"
    if [ -d /run/systemd/system ]; then
      install -d -m 0755 /run/sshd
      /usr/sbin/sshd -t
      mc_node_ssh_config=$(/usr/sbin/sshd -T)
      if ! printf '%s\n' "$mc_node_ssh_config" | grep -Fx 'authorizedkeyscommand /usr/lib/mission-core-node/node-agent ssh-keys %u' >/dev/null; then
        echo "Mission Core Node: another AuthorizedKeysCommand overrides Node SSH access. Existing configuration was preserved; resolve this conflict before accepting setup." >&2
        exit 1
      fi
      if ! printf '%s\n' "$mc_node_ssh_config" | grep -Fx 'authorizedkeyscommanduser mission-core-node' >/dev/null; then
        echo "Mission Core Node: conflicting AuthorizedKeysCommandUser; existing configuration was preserved." >&2
        exit 1
      fi
      systemctl daemon-reload
      systemctl enable --now ssh.service
      systemctl try-reload-or-restart ssh.service
      systemctl enable mission-core-node.service
      systemctl restart mission-core-node.service
    fi
    ;;
esac
