#!/usr/bin/env bash
# Start de self-update en wacht tot GET /api/v1/admin/self-update
# status ok meldt voor CI_COMMIT_SHA. publish_aur heeft needs: [self_update],
# dus die job start pas hierna. Een mislukking of timeout faalt deze job.
# SELF_UPDATE_TIMEOUT is seconden (standaard 300). SELF_UPDATE_INTERVAL
# is de pauze tussen pogingen (standaard 5).
set -euo pipefail

: "${CI_API_URL:?CI_API_URL ontbreekt}"
: "${BLUEGIT_UPDATE_TOKEN:?BLUEGIT_UPDATE_TOKEN ontbreekt}"
: "${CI_COMMIT_SHA:?CI_COMMIT_SHA ontbreekt}"

timeout="${SELF_UPDATE_TIMEOUT:-300}"
interval="${SELF_UPDATE_INTERVAL:-5}"
[[ "$timeout" =~ ^[0-9]+$ ]] || timeout=300
[[ "$interval" =~ ^[0-9]+$ ]] || interval=5

if ! command -v jq >/dev/null 2>&1; then
  apk add --no-cache jq >&2
fi

api="${CI_API_URL%/}/admin/self-update"
auth=(-H "Authorization: Bearer ${BLUEGIT_UPDATE_TOKEN}")

curl -fsS --connect-timeout 5 --max-time 20 -X POST "$api" "${auth[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"ref\":\"${CI_COMMIT_SHA}\"}"

start="$(date +%s)"
while true; do
  # Een herstart van de service tijdens pacman -U mag de poll niet stoppen.
  # log staat live als eerste key en bevat de tekst "status" en "sha".
  body="$(curl -fsS --connect-timeout 5 --max-time 20 "$api" "${auth[@]}" || true)"
  status=""
  sha=""
  if parsed="$(printf '%s' "$body" | jq -er '[.status // "", .sha // ""] | @tsv' 2>/dev/null)"; then
    status="${parsed%%$'\t'*}"
    sha="${parsed#*$'\t'}"
  fi
  if [[ "$sha" == "$CI_COMMIT_SHA" && "$status" == "ok" ]]; then
    echo "Self-update ok: $sha"
    exit 0
  fi
  if [[ "$sha" == "$CI_COMMIT_SHA" && "$status" == "failed" ]]; then
    echo "Self-update mislukt: $sha" >&2
    exit 1
  fi
  now="$(date +%s)"
  if (( now - start >= timeout )); then
    echo "Self-update timeout na ${timeout}s (status ${status:-onbekend}, sha ${sha:-onbekend})" >&2
    exit 1
  fi
  echo "Self-update status ${status:-onbekend} voor ${sha:-onbekend}"
  sleep "$interval"
done
