#!/usr/bin/env bash
# Bring up Gitea, create the admin user and the galaxy/galaxy repo,
# fetch a runner registration token, bring up the runner.
# Idempotent — re-runnable.
set -euo pipefail

cd "$(dirname "$0")"

GITEA_USER=galaxy
GITEA_PASS=galaxy-dev
GITEA_EMAIL=galaxy@local
REPO_NAME=galaxy
GITEA_URL=http://localhost:3000

echo ">>> Bringing up Gitea..."
docker compose up -d gitea

echo ">>> Waiting for Gitea API..."
for _ in $(seq 1 120); do
    if curl -fsS "${GITEA_URL}/api/v1/version" >/dev/null 2>&1; then
        echo "Gitea is up."
        break
    fi
    sleep 1
done

if ! curl -fsS "${GITEA_URL}/api/v1/version" >/dev/null 2>&1; then
    echo "Gitea did not come up within 120 seconds." >&2
    docker compose logs gitea | tail -30 >&2
    exit 1
fi

echo ">>> Creating admin user (idempotent)..."
docker compose exec -T gitea su git -c "
    gitea admin user create \
        --username ${GITEA_USER} \
        --password ${GITEA_PASS} \
        --email ${GITEA_EMAIL} \
        --admin \
        --must-change-password=false 2>&1 || true
"

echo ">>> Creating repo (idempotent)..."
HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' \
    -u "${GITEA_USER}:${GITEA_PASS}" \
    -H "Content-Type: application/json" \
    -d "{\"name\":\"${REPO_NAME}\",\"private\":true,\"auto_init\":false}" \
    "${GITEA_URL}/api/v1/user/repos")
case "${HTTP_CODE}" in
    201) echo "Repo created." ;;
    409) echo "Repo already exists." ;;
    *)
        echo "Unexpected response (${HTTP_CODE}) creating repo." >&2
        exit 1
        ;;
esac

echo ">>> Fetching runner registration token..."
RUNNER_TOKEN=$(curl -fsS \
    -u "${GITEA_USER}:${GITEA_PASS}" \
    "${GITEA_URL}/api/v1/admin/runners/registration-token" \
    | python3 -c "import json, sys; print(json.load(sys.stdin)['token'])")

# act_runner uses RUNNER_TOKEN only on the first boot. After registration
# it persists credentials in the named runner-data volume (/data/.runner)
# and ignores the env token on subsequent restarts. Writing a fresh token
# every time is harmless.
echo "RUNNER_TOKEN=${RUNNER_TOKEN}" > .env

echo ">>> Bringing up runner..."
docker compose up -d runner

cat <<EOF

Done.

Push the current branch and watch a run:

    cd $(cd ../.. && pwd)
    git remote add local-gitea http://${GITEA_USER}:${GITEA_PASS}@localhost:3000/${GITEA_USER}/${REPO_NAME}.git 2>/dev/null || true
    git push local-gitea HEAD

    open http://localhost:3000/${GITEA_USER}/${REPO_NAME}/actions

Or use \`make push\` from this directory.
EOF
