#!/usr/bin/env bash
set -euo pipefail

# === CONFIG ===
GITEA_URL="${GITEA_URL:-https://git.azuredevops.co.uk}"   # or export GITEA_URL=...
REG_TOKEN="tQ6K7y2adPYg7Nh1gt0pWrYbBOxkPPcHjfcvfqHE"                          # export REG_TOKEN=... (required)
HOSTNAME_VAL="$(hostname)"
RUNNER_NAME="${RUNNER_NAME:-${HOSTNAME_VAL}-runner}"
RUNNER_LABELS="${RUNNER_LABELS:-${HOSTNAME_VAL}}"
WORK_DIR="${WORK_DIR:-/root/act_runner}"
VERSION="v0.2.13"
FILE_VER="${VERSION#v}"
BINARY_URL="https://gitea.com/gitea/act_runner/releases/download/${VERSION}/act_runner-${FILE_VER}-linux-amd64"
SERVICE_NAME="gitea-act-runner"

if [[ -z "$REG_TOKEN" ]]; then
  echo "❌ REG_TOKEN not set. export REG_TOKEN=<runner token> and re-run."
  exit 1
fi

mkdir -p "$WORK_DIR"
cd "$WORK_DIR"

# --- download binary ---
if [[ ! -x "${WORK_DIR}/act_runner" ]]; then
  echo "⬇️  Downloading act_runner ${VERSION}…"
  curl -fL "$BINARY_URL" -o act_runner
  chmod +x act_runner
fi

# --- config.yml (Docker default image + hostname label) ---
if [[ ! -f "${WORK_DIR}/config.yml" ]]; then
  cat > "${WORK_DIR}/config.yml" <<EOF
log:
  level: info
runner:
  capacity: 1
  envs: {}
  labels:
    - "${HOSTNAME_VAL}:docker://reg.azuredevops.co.uk/alma:latest"
  fetch_timeout: 30s
  idle_timeout: 30s
EOF
fi

# --- register runner (only once) ---
if [[ ! -f "${WORK_DIR}/.runner" ]]; then
  echo "📝 Registering runner ${RUNNER_NAME} @ ${GITEA_URL}"
  ./act_runner register --no-interactive \
    --instance "$GITEA_URL" \
    --token "$REG_TOKEN" \
    --name "$RUNNER_NAME" \
    --labels "$RUNNER_LABELS"
else
  echo "ℹ️  Runner already registered (.runner exists)."
fi

# --- systemd unit (runs as root) ---
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<UNIT
[Unit]
Description=Gitea Act Runner
Wants=network-online.target docker.service
After=network-online.target docker.service

[Service]
User=root
Group=root
WorkingDirectory=${WORK_DIR}
ExecStart=${WORK_DIR}/act_runner daemon
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
UNIT

# --- enable & start ---
systemctl daemon-reload
systemctl enable --now "${SERVICE_NAME}"

echo
echo "✅ Service installed & started: ${SERVICE_NAME}"
echo "   Status: systemctl status ${SERVICE_NAME}"
echo "   Logs:   journalctl -u ${SERVICE_NAME} -f"
