#!/usr/bin/env bash

###############################################################################
# register-runner.sh — GitLab Runner registration helper
#
# Registers the Docker-based GitLab Runner against your GitLab CE instance.
# Designed to work with the gitlab-docker-compose.yml stack.
#
# Usage:
#   ./register-runner.sh <runner-token>
#   ./register-runner.sh glrt-xxxxxxxxxxxxxxxxxxxx
#
# The runner token is obtained from:
#   Admin Area → CI/CD → Runners → New instance runner → Create runner
#
# Author: Phil Connor
# Contact: contact@mylinux.work
# License: MIT
###############################################################################

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────
GITLAB_HOSTNAME="${GITLAB_HOSTNAME:-gitlab.local}"
RUNNER_CONTAINER="${RUNNER_CONTAINER:-gitlab-runner}"
RUNNER_EXECUTOR="${RUNNER_EXECUTOR:-docker}"
RUNNER_IMAGE="${RUNNER_IMAGE:-alpine:latest}"
RUNNER_DESCRIPTION="${RUNNER_DESCRIPTION:-docker-runner}"
RUNNER_TAGS="${RUNNER_TAGS:-docker,linux}"

# ── Colors ────────────────────────────────────────────────────────────
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    BOLD='\033[1m'
    RESET='\033[0m'
else
    RED="" GREEN="" YELLOW="" BOLD="" RESET=""
fi

log()  { echo -e "${GREEN}[OK]${RESET} $*"; }
warn() { echo -e "${YELLOW}[WARN]${RESET} $*" >&2; }
err()  { echo -e "${RED}[ERROR]${RESET} $*" >&2; }

# ── Validation ────────────────────────────────────────────────────────
if [[ $# -lt 1 ]]; then
    echo -e "${BOLD}Usage:${RESET} $(basename "$0") <runner-token>"
    echo ""
    echo "Get the token from: Admin Area → CI/CD → Runners → New instance runner"
    echo ""
    echo "Environment variables:"
    echo "  GITLAB_HOSTNAME     GitLab server hostname (default: gitlab.local)"
    echo "  RUNNER_CONTAINER    Runner container name (default: gitlab-runner)"
    echo "  RUNNER_EXECUTOR     Executor type (default: docker)"
    echo "  RUNNER_IMAGE        Default CI image (default: alpine:latest)"
    echo "  RUNNER_DESCRIPTION  Runner description (default: docker-runner)"
    echo "  RUNNER_TAGS         Comma-separated tags (default: docker,linux)"
    exit 1
fi

RUNNER_TOKEN="$1"

# Verify the runner container is running
if ! docker inspect "$RUNNER_CONTAINER" &>/dev/null; then
    err "Container '${RUNNER_CONTAINER}' not found. Is the stack running?"
    err "Run: docker compose up -d"
    exit 1
fi

if [[ "$(docker inspect -f '{{.State.Running}}' "$RUNNER_CONTAINER" 2>/dev/null)" != "true" ]]; then
    err "Container '${RUNNER_CONTAINER}' is not running."
    exit 1
fi

# ── Register ──────────────────────────────────────────────────────────
echo -e "${BOLD}Registering GitLab Runner...${RESET}"
echo "  GitLab URL:   https://${GITLAB_HOSTNAME}"
echo "  Executor:     ${RUNNER_EXECUTOR}"
echo "  Default image: ${RUNNER_IMAGE}"
echo "  Tags:         ${RUNNER_TAGS}"
echo "  Description:  ${RUNNER_DESCRIPTION}"
echo ""

docker exec "$RUNNER_CONTAINER" gitlab-runner register \
    --non-interactive \
    --url "https://${GITLAB_HOSTNAME}" \
    --token "$RUNNER_TOKEN" \
    --executor "$RUNNER_EXECUTOR" \
    --docker-image "$RUNNER_IMAGE" \
    --description "$RUNNER_DESCRIPTION" \
    --tag-list "$RUNNER_TAGS" \
    --docker-network-mode "gitlab-net" \
    --docker-volumes "/var/run/docker.sock:/var/run/docker.sock"

echo ""

# ── Verify ────────────────────────────────────────────────────────────
if docker exec "$RUNNER_CONTAINER" gitlab-runner list 2>&1 | grep -q "$RUNNER_DESCRIPTION"; then
    log "Runner registered successfully."
    echo ""
    docker exec "$RUNNER_CONTAINER" gitlab-runner list
else
    warn "Registration completed but runner not found in list. Check logs:"
    echo "  docker compose logs gitlab-runner"
fi
