#!/usr/bin/env bash
# Installe act_runner sur le serveur de déploiement (runner "host").
# Prérequis : Docker, git, curl, nodejs >= 20, accès root.
# Variables : GITEA_URL, RUNNER_TOKEN, RUNNER_NAME, RUNNER_LABELS.
set -Eeuo pipefail

: "${GITEA_URL:?GITEA_URL est obligatoire (ex: https://git.mairie-grimaud.fr)}"
: "${RUNNER_TOKEN:?RUNNER_TOKEN est obligatoire (jeton fourni par Gitea)}"

RUNNER_NAME="${RUNNER_NAME:-$(hostname)}"
RUNNER_LABELS="${RUNNER_LABELS:-linux:host,production:host}"
ACT_RUNNER_VERSION="${ACT_RUNNER_VERSION:-0.2.11}"

log() { printf '[runner] %s\n' "$*"; }

for cmd in docker git curl; do
    command -v "$cmd" >/dev/null 2>&1 || { log "$cmd est requis."; exit 1; }
done

case "$(uname -m)" in
    x86_64|amd64) ARCH="amd64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    *) log "Architecture non prise en charge : $(uname -m)"; exit 1 ;;
esac

log "Téléchargement d'act_runner ${ACT_RUNNER_VERSION} (${ARCH})..."
curl -fsSL -o /usr/local/bin/act_runner \
    "https://gitea.com/gitea/act_runner/releases/download/v${ACT_RUNNER_VERSION}/act_runner-${ACT_RUNNER_VERSION}-linux-${ARCH}"
chmod 0755 /usr/local/bin/act_runner

mkdir -p /etc/act_runner
cd /etc/act_runner

if [ ! -f config.yaml ]; then
    act_runner generate-config > config.yaml
fi

log "Enregistrement du runner ${RUNNER_NAME} (labels: ${RUNNER_LABELS})..."
act_runner register \
    --no-interactive \
    --instance "$GITEA_URL" \
    --token "$RUNNER_TOKEN" \
    --name "$RUNNER_NAME" \
    --labels "$RUNNER_LABELS"

cat > /etc/systemd/system/gitea-runner.service <<'UNIT'
[Unit]
Description=Gitea Actions Runner
After=docker.service network-online.target
Requires=docker.service

[Service]
Type=simple
WorkingDirectory=/etc/act_runner
ExecStart=/usr/local/bin/act_runner daemon --config /etc/act_runner/config.yaml
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now gitea-runner
systemctl --no-pager --full status gitea-runner || true

log "Runner installé. Vérifiez sa présence dans Gitea : Admin > Actions > Runners."
