#!/bin/bash
# import-variables.sh
# Import GitLab admin CI/CD variables from JSON input
# Usage:
#   ./import-variables.sh [--input filename.json] [--force]
#   ./import-variables.sh --help

set -euo pipefail

INPUT="/dev/stdin"
FORCE=false

print_help() {
  cat <<EOF
Usage: $0 [--input filename.json] [--force]

Options:
  --input FILE     Read variables from FILE instead of stdin
  --force          Overwrite existing variables if they already exist
  --help           Show this help message

Environment:
  SELF_GITLAB_TOKEN must be set to a GitLab admin access token

Example:
  $0 --input vars.json
  cat vars.json | $0 --force
EOF
  exit 0
}

# Parse args
while [[ $# -gt 0 ]]; do
  case "$1" in
  --input)
    INPUT="$2"
    shift 2
    ;;
  --force)
    FORCE=true
    shift
    ;;
  --help)
    print_help
    ;;
  *)
    echo "Unknown option: $1"
    print_help
    ;;
  esac
done

: "${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

# Read and process each variable
jq -c '.[]' "$INPUT" | while read -r var; do
  KEY=$(echo "$var" | jq -r '.key')
  VALUE=$(echo "$var" | jq -r '.value')
  PROTECTED=$(echo "$var" | jq -r '.protected')
  MASKED=$(echo "$var" | jq -r '.masked')
  VARIABLE_TYPE=$(echo "$var" | jq -r '.variable_type')

  # Check if variable already exists
  EXISTS=$(curl --silent --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
    "https://gitlab.ellisbs.co.uk/api/v4/admin/ci/variables/$KEY" \
    --write-out "%{http_code}" --output /dev/null)

  if [[ $EXISTS == "200" ]]; then
    echo "Variable '$KEY' already exists."

    if [[ $FORCE == true ]]; then
      echo "  --force enabled: overwriting '$KEY'."
      curl --silent --request PUT "https://gitlab.ellisbs.co.uk/api/v4/admin/ci/variables/$KEY" \
        --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
        --header "Content-Type: application/json" \
        --data "{
          \"value\": \"$VALUE\",
          \"protected\": $PROTECTED,
          \"masked\": $MASKED,
          \"variable_type\": \"$VARIABLE_TYPE\"
        }" >/dev/null
    fi
  else
    echo "Creating new variable '$KEY'."
    curl --silent --request POST "https://gitlab.ellisbs.co.uk/api/v4/admin/ci/variables" \
      --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
      --header "Content-Type: application/json" \
      --data "{
        \"key\": \"$KEY\",
        \"value\": \"$VALUE\",
        \"protected\": $PROTECTED,
        \"masked\": $MASKED,
        \"variable_type\": \"$VARIABLE_TYPE\"
      }" >/dev/null
  fi
done
