#!/usr/bin/env bash
#
# v0.13-DEDICATED-RUNNER — set up a Linux VPS (or mini-PC) as the
# acc-runner host via a systemd user unit.
#
# Idempotent: re-running rewrites the unit file and restarts the
# service. enable-linger is checked before re-enabling so SSH-less
# operators don't see a spurious prompt.
#
# RUNNER-LINUX-SUPERVISOR-1: `--instance <name>` supervises a NAMED
# runner instance. The name forks the unit (acc-runner-<name>.service),
# the ExecStart (`watch --instance <name>`) and ACC_RUNNER_INSTANCE, so
# several named instances coexist on one host instead of overwriting the
# single acc-runner.service they used to share. Without the flag every
# rendered byte is what it was before — existing hosts are unaffected.
#
# Usage:
#   packages/acc-runner/scripts/setup-dedicated-runner-linux.sh
#   packages/acc-runner/scripts/setup-dedicated-runner-linux.sh --instance staging-smoke
#   packages/acc-runner/scripts/setup-dedicated-runner-linux.sh --help
#
# Secrets are never written to the unit — tokens live in the OS keychain
# (per instance: `acc-runner login --instance <name>`).
#
# Verify:   acc-runner doctor --instance <name>   (checks this unit)
# See docs/acc/DEDICATED_RUNNER_RUNBOOK.md.

set -euo pipefail

INSTANCE=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --instance)
      INSTANCE="${2:-}"
      [[ -n "$INSTANCE" ]] || { echo "setup-dedicated-runner-linux.sh: --instance needs a name" >&2; exit 2; }
      shift 2
      ;;
    --instance=*) INSTANCE="${1#*=}"; shift ;;
    -h|--help)
      awk 'NR>=2 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "${BASH_SOURCE[0]}"
      exit 0
      ;;
    *) echo "setup-dedicated-runner-linux.sh: unknown option '$1' (see --help)" >&2; exit 2 ;;
  esac
done

# Mirrors INSTANCE_NAME_RE in packages/acc-runner/src/instance.ts. The name
# lands in a unit name and a keychain account, so nothing escapable is allowed.
if [[ -n "$INSTANCE" && ! "$INSTANCE" =~ ^[a-z0-9][a-z0-9-]{0,31}$ ]]; then
  echo "setup-dedicated-runner-linux.sh: invalid --instance '$INSTANCE'" >&2
  echo "  must match ^[a-z0-9][a-z0-9-]{0,31}$ (lowercase, digits, dashes)" >&2
  exit 2
fi

if [[ "$(uname)" != "Linux" ]]; then
  echo "setup-dedicated-runner-linux.sh: Linux-only (uname=$(uname))" >&2
  exit 1
fi

ACC_RUNNER_PATH="$(command -v acc-runner || true)"
if [[ -z "$ACC_RUNNER_PATH" ]]; then
  echo "acc-runner not found in PATH. Install: sudo npm install -g @tokenfactory/acc-runner" >&2
  exit 1
fi

if ! command -v systemctl >/dev/null 2>&1; then
  echo "systemctl not found; this script requires systemd." >&2
  exit 1
fi

UNIT_DIR="$HOME/.config/systemd/user"
SERVICE="acc-runner${INSTANCE:+-$INSTANCE}"
UNIT="$UNIT_DIR/$SERVICE.service"
LOG_HINT="journalctl --user -u $SERVICE -f"
mkdir -p "$UNIT_DIR"

# 1. Render the unit file. systemd-inhibit blocks logind's automatic idle
#    action while the runner is active (a no-op on always-on VPS instances,
#    real protection on a desktop/mini-PC).
#
#    `--what=idle`, NOT `idle:sleep`. The two halves are separate polkit
#    actions and they do not have the same default:
#
#      org.freedesktop.login1.inhibit-block-idle    allow_any=yes
#      org.freedesktop.login1.inhibit-block-sleep   allow_any=no
#
#    This unit runs as a child of a lingering user@<uid>.service, which has no
#    logind session, so polkit evaluates the `allow_any` branch. Requesting
#    `idle:sleep` therefore took the sleep action's `no`, systemd-inhibit
#    exited 1 BEFORE exec'ing the runner, and Restart=always turned that into a
#    permanent 60s restart loop in which acc-runner never ran at all (observed
#    on a live VPS: `Failed to inhibit: Access denied`, CPU 3ms per attempt).
#    `idle` alone is allow_any=yes, so it succeeds unprivileged and
#    session-less on the stock policy.
#
#    Dropping `sleep` costs nothing a runner host wants: it only blocked an
#    explicit `systemctl suspend`, while `idle` is what blocks the automatic
#    IdleAction suspend the runbook actually describes.
#
#    Deliberately NOT gated on an install-time capability probe. The installer
#    runs in the operator's logind session, which is `active`, so a probe would
#    take polkit's allow_active branch and pass -- then the unit runs
#    session-less at boot and fails anyway. A probe would ship this outage
#    under the appearance of a fix.
INHIBIT_PATH="$(command -v systemd-inhibit || true)"

# packages/acc-runner/src/cli.ts is `#!/usr/bin/env node`, so an absolute
# ACC_RUNNER_PATH in ExecStart still resolves `node` against the unit's OWN
# PATH. A node from nvm/fnm/volta lives under $HOME and is not on the system
# path below, which exits 127 -- another silent restart loop, and the next
# failure after the inhibit one on any host that did not install node via apt.
# install-launchd.sh already solves this on macOS (resolve_node_bin_dir); this
# is the Linux counterpart, kept minimal: the installer runs in the operator's
# shell, where the intended node is already resolvable.
UNIT_PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
NODE_BIN_DIR="$(cd "$(dirname "$(command -v node)")" 2>/dev/null && pwd || true)"
case ":$UNIT_PATH:" in
  *":$NODE_BIN_DIR:"*) ;;
  *) [[ -n "$NODE_BIN_DIR" ]] && UNIT_PATH="$NODE_BIN_DIR:$UNIT_PATH" ;;
esac

# Render the unit from the ONE canonical template (renderSystemdUnit in
# supervisor.ts), exposed as `acc-runner print-systemd-unit`, instead of this
# script keeping its own heredoc. That template carries
# RestartPreventExitStatus=78 (RUNNER-REFRESH-ROTATION-LOST) — a terminal
# refresh refusal leaves the unit FAILED rather than restart-looping every
# RestartSec and burning the token family. ACC_RUNNER_INSTANCE (named installs),
# the systemd-inhibit wrapper and the node-bin PATH all flow through as flags,
# so the installer and the doctor read from a single renderer.
UNIT_ARGS=(print-systemd-unit --exec-path "$ACC_RUNNER_PATH" --env-path "$UNIT_PATH")
[[ -n "$INSTANCE" ]] && UNIT_ARGS+=(--instance "$INSTANCE")
[[ -n "$INHIBIT_PATH" ]] && UNIT_ARGS+=(--inhibit-path "$INHIBIT_PATH")
# `env -u ACC_RUNNER_INSTANCE`: the instance must come ONLY from the --instance
# flag ($INSTANCE), as the old heredoc did — not from an ACC_RUNNER_INSTANCE the
# operator happens to have exported. Otherwise an unnamed install (no flag) would
# render a unit body naming that ambient instance while still being written to
# the unnamed acc-runner.service path. The flag re-sets the env for the CLI.
env -u ACC_RUNNER_INSTANCE "$ACC_RUNNER_PATH" "${UNIT_ARGS[@]}" > "$UNIT"

# 2. enable-linger so the unit survives the operator's SSH disconnect.
if ! loginctl show-user "$USER" 2>/dev/null | grep -q "Linger=yes"; then
  echo "Enabling linger for $USER (requires sudo)..."
  sudo loginctl enable-linger "$USER"
fi

# 3. Reload + start.
systemctl --user daemon-reload
systemctl --user enable --now "$SERVICE.service"

echo "Installed $UNIT"
echo "Service active: $(systemctl --user is-active "$SERVICE.service")"
echo "Logs: $LOG_HINT"
echo "Verify: acc-runner doctor${INSTANCE:+ --instance $INSTANCE}"
echo "Uninstall: systemctl --user disable --now $SERVICE && rm \"$UNIT\" && sudo loginctl disable-linger $USER"
