#!/bin/bash -efux

# -----------------------------------------------------------------------------
# Important: this scripts depends on some predefined environment variables:
# - GITLAB_REGISTRATION_TOKEN (required): registration token for your project
# - CONCURRENT (optional): Limits how many jobs can run concurrently.
# - GITLAB_URL (optional): the URL to the GitLab instance (defaults to https://gitlab.com)
# - RUNNER_TAG_LIST (optional): comma separated list of tags for the runner
# - REGISTER_RUN_UNTAGGED (required): registered runner will process untagged jobs or not
# -----------------------------------------------------------------------------

# Limits how many jobs can run concurrently. The maximum number is all defined runners.
export CONCURRENT=${CONCURRENT:=10}

# Default to https://gitlab.zivver.org if the GitLab URL was not specified
export GITLAB_URL=${GITLAB_URL:=https://gitlab.com}

# gitlab-runner data directory
DATA_DIR="/etc/gitlab-runner"
CONFIG_FILE=${CONFIG_FILE:-$DATA_DIR/config.toml}
# custom certificate authority path
CA_CERTIFICATES_PATH=${CA_CERTIFICATES_PATH:-$DATA_DIR/certs/ca.crt}
LOCAL_CA_PATH="/usr/local/share/ca-certificates/ca.crt"

###############################################################################
# Remove the Runner from the list of runners of the project identified by the
# authentication token.
#
# Arguments:
#   $auth_token - Authorization token obtained after registering the runner in the
#        project
###############################################################################
unregister_runner() {
    local signal="$?"
    echo "Unregister runner with signal $signal"
    [ -n "$auth_token" ] && \
	gitlab-runner unregister --url "${GITLAB_URL}" --token "$auth_token"
	exit $signal
}

trap unregister_runner INT QUIT TERM KILL

###############################################################################
# Register the Runner in the desired project, identified by the registration
# token of that project.
#
# The function populates the "auth_token" variable with the authentication
# token for the registered Runner.
#
# Arguments:
#   $1 - Group ID
#   $2 - Registration token
#   $3 - List of tags for the Runner, separated by comma
###############################################################################
register_runner() {

    runner_identification="Gitlab ${EXECUTOR} runner $(date +%s)"

    # Uses the environment variable "GITLAB_REGISTRATION_TOKEN" to register the runner
    result_json=$(
        curl --request POST "${GITLAB_URL}/api/v4/user/runners" \
            --data "runner_type=group_type" \
	    --data "group_id=$1" \
            --data "description=${runner_identification}" \
            --data "tag_list=$3" \
            --data "run_untagged=${REGISTER_RUN_UNTAGGED}" \
            --header "PRIVATE-TOKEN: $2"
    )

    # Read the authentication token
    auth_token=$(echo "$result_json" | jq -r '.token')

    # Recreate the runner config.toml based on our template
    export RUNNER_AUTH_TOKEN=$auth_token
    # skip envsubst substitution
    export CI_RUNNER_VERSION='${CI_RUNNER_VERSION}'
    envsubst < /tmp/config.toml.template > /etc/gitlab-runner/config.toml
    printf '%s\n' "$RUNNER_AUTH_TOKEN"
}

update_ca() {
	  echo "Updating CA certificates..."
	    cp "${CA_CERTIFICATES_PATH}" "${LOCAL_CA_PATH}"
	      update-ca-certificates --fresh >/dev/null
      }

if [ -n "${GITLAB_REGISTRATION_TOKEN:-}" ]; then

    export auth_token=$(register_runner "${GITLAB_GROUP_ID}" "${GITLAB_REGISTRATION_TOKEN}" "${RUNNER_TAG_LIST}")
    echo "auth_token is $auth_token"

    if [ -f "${CA_CERTIFICATES_PATH}" ]; then
    	  # update the ca if the custom ca is different than the current
    	    cmp --silent "${CA_CERTIFICATES_PATH}" "${LOCAL_CA_PATH}" || update_ca
    fi

    # Gitlab runner run will block the script until a docker stop is emited
    gitlab-runner --debug run --user=gitlab-runner --working-directory=/home/gitlab-runner & pid="$!"
    # wait forever
    while true
    do
      tail -f /dev/null & wait ${!}
    done
else
  exec "$@"
fi
