#!/usr/bin/env bash

set -Eeuo pipefail

GITLAB_URL="${GITLAB_URL:-https://gitlab.konturai.kz/}"
RUNNER_NAME="${RUNNER_NAME:-call-center-prod-runner}"
RUNNER_TAGS="${RUNNER_TAGS:-call-center-prod}"
RUNNER_EXECUTOR="${RUNNER_EXECUTOR:-shell}"
RUNNER_TOKEN="${RUNNER_TOKEN:-}"
DEPLOY_DIR="${DEPLOY_DIR:-/home/gitlab-runner/deploy/call-center}"
SKIP_REGISTER="${SKIP_REGISTER:-0}"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run this script as root." >&2
  exit 1
fi

if [[ "$SKIP_REGISTER" != "1" && -z "$RUNNER_TOKEN" ]]; then
  echo "Set RUNNER_TOKEN from GitLab project/group runner settings before running this script." >&2
  exit 1
fi

apt-get update
apt-get install -y ca-certificates curl

if ! command -v gitlab-runner >/dev/null 2>&1; then
  curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | bash
  apt-get install -y gitlab-runner
fi

if ! getent group docker >/dev/null 2>&1; then
  echo "Docker group does not exist. Install Docker before registering the runner." >&2
  exit 1
fi

usermod -aG docker gitlab-runner
install -d -o gitlab-runner -g gitlab-runner "$(dirname "$DEPLOY_DIR")"
install -d -o gitlab-runner -g gitlab-runner "$DEPLOY_DIR"

if [[ "$SKIP_REGISTER" == "1" ]]; then
  echo "gitlab-runner installed. Registration skipped because SKIP_REGISTER=1."
elif gitlab-runner list 2>/dev/null | grep -Fq "$RUNNER_NAME"; then
  echo "Runner $RUNNER_NAME is already registered."
else
  register_args=(
    --non-interactive
    --url "$GITLAB_URL"
    --executor "$RUNNER_EXECUTOR"
    --description "$RUNNER_NAME"
    --tag-list "$RUNNER_TAGS"
    --run-untagged="false"
    --locked="true"
  )
  if [[ "$RUNNER_TOKEN" == glrt-* ]]; then
    register_args+=(--token "$RUNNER_TOKEN")
  else
    register_args+=(--registration-token "$RUNNER_TOKEN")
  fi
  gitlab-runner register "${register_args[@]}"
fi

systemctl enable --now gitlab-runner
systemctl restart gitlab-runner
if [[ "$SKIP_REGISTER" != "1" ]]; then
  gitlab-runner verify
fi

if [[ "$SKIP_REGISTER" == "1" ]]; then
  echo "gitlab-runner service is installed and running."
else
  echo "Runner $RUNNER_NAME is ready."
fi
