#!/bin/bash
# Setup Gitea Act Runner on this machine (host mode)
# Usage: bash scripts/setup-runner.sh <registration-token>

set -e

TOKEN="${1:?Usage: $0 <registration-token>}"
INSTANCE="https://git.euphon.cloud"
RUNNER_NAME="hera-runner"
RUNNER_BIN="$HOME/bin/act_runner"
VERSION="v0.2.11"

echo "=== Installing act_runner ${VERSION} ==="
mkdir -p "$HOME/bin"
curl -L "https://gitea.com/gitea/act_runner/releases/download/${VERSION}/act_runner-${VERSION}-linux-amd64" \
  -o "$RUNNER_BIN"
chmod +x "$RUNNER_BIN"
echo "Installed: $($RUNNER_BIN --version)"

echo ""
echo "=== Registering runner ==="
cd "$HOME"
$RUNNER_BIN register --no-interactive \
  --instance "$INSTANCE" \
  --token "$TOKEN" \
  --name "$RUNNER_NAME" \
  --labels "ubuntu-latest:host"

echo ""
echo "=== Setting up systemd user service ==="
mkdir -p "$HOME/.config/systemd/user"
cat > "$HOME/.config/systemd/user/act-runner.service" << EOF
[Unit]
Description=Gitea Act Runner
After=network.target

[Service]
Type=simple
WorkingDirectory=%h
ExecStart=%h/bin/act_runner daemon
Restart=on-failure
RestartSec=10

[Install]
WantedBy=default.target
EOF

systemctl --user daemon-reload
systemctl --user enable act-runner
systemctl --user start act-runner

echo ""
echo "=== Done! ==="
systemctl --user status act-runner --no-pager | head -8
echo ""
echo "Check Gitea → Settings → Actions → Runners to verify."
