#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Registers the runner on first boot (if no .runner state exists in /data),
# then runs the act_runner daemon. Idempotent: on subsequent boots it reuses
# the stored registration and ignores the token.
set -euo pipefail

CONFIG_FILE="${CONFIG_FILE:-/data/config.yaml}"

cd /data

# Seed the config from the image's template on first boot so it lives in the
# persistent volume and can be edited there.
if [ ! -f "$CONFIG_FILE" ]; then
    cp /etc/act_runner/config.yaml "$CONFIG_FILE"
fi

# runner.file in config.yaml is ".runner" (relative to this CWD => /data/.runner).
if [ ! -f /data/.runner ]; then
    if [ -z "${GITEA_RUNNER_REGISTRATION_TOKEN:-}" ]; then
        echo "ERROR: no /data/.runner registration and GITEA_RUNNER_REGISTRATION_TOKEN is empty." >&2
        echo "       Grab a token from the repo's Settings -> Actions -> Runners and set it" >&2
        echo "       in the Quadlet unit for the first boot only." >&2
        exit 1
    fi
    echo "Registering runner '${GITEA_RUNNER_NAME:-podman}' with ${GITEA_INSTANCE_URL} ..."
    act_runner register --no-interactive \
        --config   "$CONFIG_FILE" \
        --instance "${GITEA_INSTANCE_URL:?set GITEA_INSTANCE_URL}" \
        --token    "$GITEA_RUNNER_REGISTRATION_TOKEN" \
        --name     "${GITEA_RUNNER_NAME:-podman}" \
        --labels   "${GITEA_RUNNER_LABELS:-ubuntu-latest:host}"
fi

exec act_runner daemon --config "$CONFIG_FILE"
