#!/usr/bin/env bash
# ==============================================================================
# alfred-support-access — Opt-In Timed Support SSH Access Manager (v7.5.118)
# Never touches existing keys automatically. Lets any node owner grant temporary
# support access (with automatic expiry via systemd-run) and revoke in 1 command.
# ==============================================================================
set -euo pipefail

SUPPORT_MARKER="# ALFRED-SUPPORT-OPT-IN"
SUPPORT_PUBKEY_FILE="/etc/alfred/support-pubkey.pub"
AUTH_FILE="/root/.ssh/authorized_keys"
TIMER_UNIT="alfred-support-access-revoke"

usage() {
  cat <<'EOF'
Usage:
  alfred-support-access status
      Show whether temporary opt-in support access is currently active.

  alfred-support-access enable [--hours 4] [--pubkey-file <path>]
      Temporarily grant opt-in support SSH access for N hours (default: 4h),
      with automatic revocation scheduled via systemd timer.

  alfred-support-access revoke
      Immediately revoke opt-in support SSH access (only removes lines tagged
      with # ALFRED-SUPPORT-OPT-IN; never removes your own SSH keys).
EOF
}

require_root() {
  [ "$(id -u)" -eq 0 ] || { echo "ERROR: Run as root (sudo alfred-support-access ...)." >&2; exit 1; }
}

cmd_status() {
  if [ -f "$AUTH_FILE" ] && grep -qF "$SUPPORT_MARKER" "$AUTH_FILE" 2>/dev/null; then
    echo "SUPPORT_ACCESS=ENABLED (opt-in marker present in $AUTH_FILE)"
    systemctl list-timers --all "${TIMER_UNIT}.timer" --no-pager 2>/dev/null || true
  else
    echo "SUPPORT_ACCESS=DISABLED (no opt-in support key active in $AUTH_FILE)"
  fi
}

cmd_revoke() {
  require_root
  if [ -f "$AUTH_FILE" ] && grep -qF "$SUPPORT_MARKER" "$AUTH_FILE" 2>/dev/null; then
    local tmp
    tmp="$(mktemp)"
    grep -vF "$SUPPORT_MARKER" "$AUTH_FILE" > "$tmp" || true
    cat "$tmp" > "$AUTH_FILE"
    rm -f "$tmp"
    chmod 0600 "$AUTH_FILE"
    echo "[+] Opt-in support SSH key revoked cleanly from $AUTH_FILE."
  else
    echo "[=] No opt-in support SSH key was active."
  fi
  systemctl stop "${TIMER_UNIT}.timer" 2>/dev/null || true
  systemctl reset-failed "${TIMER_UNIT}.service" "${TIMER_UNIT}.timer" 2>/dev/null || true
}

cmd_enable() {
  require_root
  local hours="4" pubfile="$SUPPORT_PUBKEY_FILE"
  while [ $# -gt 0 ]; do
    case "$1" in
      --hours)       hours="${2:-4}"; shift 2 ;;
      --pubkey-file) pubfile="${2:-}"; shift 2 ;;
      *) echo "Unknown option: $1" >&2; usage; exit 1 ;;
    esac
  done
  [[ "$hours" =~ ^[0-9]+$ ]] && [ "$hours" -ge 1 ] && [ "$hours" -le 168 ] || { echo "ERROR: --hours must be 1..168." >&2; exit 1; }
  [ -s "$pubfile" ] || { echo "ERROR: Support public key not found at $pubfile (pass --pubkey-file <path>)." >&2; exit 1; }

  local key_line
  key_line="$(head -n 1 "$pubfile" | tr -d '\r\n')"
  [[ "$key_line" =~ ^(ssh-ed25519|ssh-rsa|ecdsa-sha2-) ]] || { echo "ERROR: Invalid public key in $pubfile." >&2; exit 1; }

  mkdir -p /root/.ssh
  chmod 0700 /root/.ssh
  touch "$AUTH_FILE"
  chmod 0600 "$AUTH_FILE"

  # Remove any previous opt-in entry first so we never duplicate
  cmd_revoke >/dev/null 2>&1 || true
  printf '%s %s\n' "$key_line" "$SUPPORT_MARKER" >> "$AUTH_FILE"

  if command -v systemd-run >/dev/null 2>&1; then
    systemd-run --unit="$TIMER_UNIT" --on-active="${hours}h" /usr/local/bin/alfred-support-access revoke >/dev/null 2>&1 || true
    echo "[+] Opt-in support access ENABLED for ${hours} hour(s) (auto-revokes automatically)."
  else
    echo "[+] Opt-in support access ENABLED. Run 'sudo alfred-support-access revoke' when finished."
  fi
}

case "${1:-}" in
  status) cmd_status ;;
  enable) shift; cmd_enable "$@" ;;
  revoke) cmd_revoke ;;
  *)      usage; exit 1 ;;
esac
