#!/bin/bash
# export-variables.sh
# Usage: ./export-variables.sh > gitlab-ci-variables.json

set -euo pipefail

: "${SELF_GITLAB_TOKEN:?SELF_GITLAB_TOKEN must be set}"

# Check if GitLab is reachable
STATUS_CODE=$(curl --silent --output /dev/null --write-out "%{http_code}" \
  --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
  "https://gitlab.ellisbs.co.uk/api/v4/version")

if [[ $STATUS_CODE -ge 500 ]]; then
  echo "❌ GitLab appears to be down (HTTP $STATUS_CODE). Please check your server status." >&2
  exit 1
elif [[ $STATUS_CODE -ge 400 ]]; then
  echo "⚠️  GitLab API responded with client error (HTTP $STATUS_CODE). Check your token or permissions." >&2
  exit 1
fi

curl --silent --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
  "https://gitlab.ellisbs.co.uk/api/v4/admin/ci/variables" | jq '.'
