#!/usr/bin/env bash
# runner_systemd_install.sh — task-2566 systemd --user service registration
# Installs a user-level systemd service so the runner survives reboot WITHOUT sudo.
# This bypasses the upstream svc.sh (which requires root) by deploying directly
# under ~/.config/systemd/user/.
#
# Idempotent: re-running will overwrite the unit file and reload systemd.
set -eu

RUNNER_DIR="${RUNNER_DIR:-/home/jay/actions-runner}"
SVC_NAME="${SVC_NAME:-github-runner.service}"
UNIT_DIR="$HOME/.config/systemd/user"
UNIT_PATH="$UNIT_DIR/$SVC_NAME"

if [[ ! -x "$RUNNER_DIR/run.sh" ]]; then
  echo "FATAL: $RUNNER_DIR/run.sh not found or not executable. Run config.sh first." >&2
  exit 1
fi

mkdir -p "$UNIT_DIR"

cat > "$UNIT_PATH" <<EOF
[Unit]
Description=GitHub Actions Self-Hosted Runner (anu-ci-runner-01)
After=network.target

[Service]
Type=simple
WorkingDirectory=$RUNNER_DIR
Environment="PATH=/home/jay/.nvm/versions/node/v24.14.0/bin:/home/jay/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="HOME=$HOME"
ExecStart=$RUNNER_DIR/run.sh
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
KillSignal=SIGTERM
TimeoutStopSec=30

[Install]
WantedBy=default.target
EOF

systemctl --user daemon-reload
systemctl --user enable "$SVC_NAME"
systemctl --user restart "$SVC_NAME"

# Enable lingering so service persists across logout (requires sudo — best-effort)
if command -v loginctl >/dev/null 2>&1; then
  loginctl enable-linger "$USER" 2>/dev/null || \
    echo "WARN: loginctl enable-linger failed (needs sudo) — service stops on logout"
fi

sleep 2
systemctl --user is-active "$SVC_NAME"
echo "OK: $SVC_NAME installed and active under user systemd"
