#!/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.
WATCH_ARGS="watch${INSTANCE:+ --instance $INSTANCE}"
INHIBIT_PATH="$(command -v systemd-inhibit || true)"
if [[ -n "$INHIBIT_PATH" ]]; then
  EXEC_LINE="ExecStart=$INHIBIT_PATH --what=idle --who=$SERVICE --why=ACC-runner-watch $ACC_RUNNER_PATH $WATCH_ARGS"
else
  EXEC_LINE="ExecStart=$ACC_RUNNER_PATH $WATCH_ARGS"
fi

# ACC_RUNNER_INSTANCE is exported into the unit so every resolver the watch
# process spawns (keychain account, cache root, machine string) agrees with the
# ExecStart flag. Appended last, so the unnamed render is unchanged.
# 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

ENV_LINES="Environment=ACC_RUNNER_DEDICATED=1
Environment=PATH=$UNIT_PATH"
if [[ -n "$INSTANCE" ]]; then
  ENV_LINES="$ENV_LINES
Environment=ACC_RUNNER_INSTANCE=$INSTANCE"
fi

cat > "$UNIT" <<EOF
[Unit]
Description=ACC runner (watch loop)${INSTANCE:+ — instance $INSTANCE}
Documentation=https://github.com/tokenfactory-pvt-ltd/agent-control-center
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
$EXEC_LINE
Restart=always
RestartSec=60s
StandardOutput=journal
StandardError=journal
$ENV_LINES

[Install]
WantedBy=default.target
EOF

# 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"
