#!/bin/bash
# gitea-runner-setup asks on the console for the number of parallel jobs and
# the runner's registration, and registers the runner. gitea-runner.path then
# starts it. gitea-runner-setup.service runs it until the runner is registered.
#
# The capacity goes to a drop-in of gitea-runner.service, which passes it to
# /etc/gitea-runner/config.yaml as CAPACITY. It is written first, because the
# runner starts as soon as it is registered.
set -euo pipefail

read -rp "Parallel jobs [1]: " capacity
[[ $capacity =~ ^[1-9][0-9]*$ ]] || capacity=1
mkdir -p /etc/systemd/system/gitea-runner.service.d
printf '[Service]\nEnvironment=CAPACITY=%s\n' "$capacity" \
  > /etc/systemd/system/gitea-runner.service.d/capacity.conf
systemctl daemon-reload

export CAPACITY=$capacity
until [[ -f /var/lib/gitea-runner/.runner ]]; do
  read -rp "Gitea URL: " url
  read -rp "Registration token: " token
  gitea-runner -c /etc/gitea-runner/config.yaml register --no-interactive \
    --instance "$url" --token "$token" || echo "Try again."
done
