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

# === CONFIG ===
GITEA_URL="${GITEA_URL:-https://git.azuredevops.co.uk}"   # or export GITEA_URL=...
REG_TOKEN="tQ6K7y2adPYg7Nh1gt0pWrYbBOxkPPcHjfcvfqHE"                            # must export REG_TOKEN
HOSTNAME_VAL="$(hostname)"
RUNNER_NAME="${RUNNER_NAME:-${HOSTNAME_VAL}-runner}"
RUNNER_LABELS="${RUNNER_LABELS:-${HOSTNAME_VAL}}"
WORK_DIR="${WORK_DIR:-$HOME/act_runner}"
VERSION="v0.2.13"
FILE_VER="${VERSION#v}"
ARCH="darwin-amd64"   # for Intel Macs. Use darwin-arm64 on Apple Silicon
BINARY_URL="https://gitea.com/gitea/act_runner/releases/download/${VERSION}/act_runner-${FILE_VER}-${ARCH}"

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} for ${ARCH}…"
  curl -fL "$BINARY_URL" -o act_runner
  chmod +x act_runner
fi

# --- config.yml ---
if [[ ! -f "${WORK_DIR}/config.yml" ]]; then
  cat > "${WORK_DIR}/config.yml" <<EOF
log:
  level: info
runner:
  capacity: 1
  envs: {}
  labels:
    - "${HOSTNAME_VAL}:docker://ztariq129/hurricane:alma-arm"
  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

echo
echo "✅ Install complete."
echo "➡️  Start runner manually with: ${WORK_DIR}/act_runner daemon"
echo "   (Optional) To run at login, create a launchd plist in ~/Library/LaunchAgents/"
