#!/usr/bin/env bash
# Checked with ShellCheck (https://www.shellcheck.net/)

# Download and configure GitHub Actions runner(s) for Kurento.
#
# To uninstall a runner, run:
#
#     sudo ./svc.sh uninstall
#     ./config.sh remove --token "$RUNNER_TOKEN"



# Shell setup
# ===========

# Bash options for strict error checking.
set -o errexit -o errtrace -o pipefail -o nounset
shopt -s inherit_errexit 2>/dev/null || true

# Trace all commands (to stderr).
#set -o xtrace



# Check dependencies
# ==================

COMMANDS=(
    jq
    tar gzip
    wget
)
for COMMAND in "${COMMANDS[@]}"; do
    command -v "$COMMAND" >/dev/null || {
        echo "ERROR: Command '$COMMAND' is not available."
        echo "Please install all dependencies: ${COMMANDS[*]}"
        exit 1
    }
done



# Settings
# ========

# Runner label. Used as label and also as prefix for runner names.
# Must be a single word (no spaces allowed).
RUNNER_LABEL="$(echo "${RUNNER_LABEL:-kurento}" | tr -d '[:space:]')"

# Number of runners to instantiate.
RUNNER_COUNT="${RUNNER_COUNT:-3}"

# Absolute path to the parent dir where runners will be configured.
RUNNER_HOME="${RUNNER_HOME:-$HOME/$RUNNER_LABEL-github-runners/}"

# GitHub registration token. Generated by the "Create self-hosted runner" page.
if [[ -z "${RUNNER_TOKEN:-}" ]]; then
    echo "ERROR: Env var RUNNER_TOKEN must be provided with a GitHub registration token"
    exit 1
fi



# Download runner package
# =======================

mkdir --parents "$RUNNER_HOME/default/"

# Prepare GitHub Actions runner.
{
    pushd "$RUNNER_HOME/default/"

    rm --force actions-runner-*.tar.gz

    wget --quiet --output-document=- "https://api.github.com/repos/actions/runner/releases/latest" \
        | jq --raw-output '.assets[].browser_download_url | select(test("linux-x64-[^-]+tar.gz$"))' \
        | wget --input-file=-

    tar -zxf actions-runner-*.tar.gz

    sudo bin/installdependencies.sh

    popd
}



# Configure runners
# =================

for RUNNER_NAME in $(printf "$RUNNER_LABEL-%02d " $(seq 1 "$RUNNER_COUNT")); do
    cp -a "$RUNNER_HOME/default/" "$RUNNER_HOME/$RUNNER_NAME/"

    pushd "$RUNNER_HOME/$RUNNER_NAME/"

    # https://docs.github.com/en/actions/hosting-your-own-runners/adding-self-hosted-runners
    ./config.sh \
        --unattended \
        --url "https://github.com/Kurento" \
        --token "$RUNNER_TOKEN" \
        --name "$RUNNER_NAME" \
        --labels "$RUNNER_LABEL" \
        --work "$RUNNER_HOME/workspace/$RUNNER_NAME/"

    # https://docs.github.com/en/actions/hosting-your-own-runners/configuring-the-self-hosted-runner-application-as-a-service
    sudo ./svc.sh install
    sudo ./svc.sh start

    popd
done



echo "Done!"
