#!/bin/sh
# AutoGovern deployment gate for CI/CD pipelines.
#
# Asks AutoGovern whether an AI system may be deployed and fails the job when
# it may not. Needs only sh and curl. Used by the GitHub Action
# (github/action.yml) and the GitLab template (gitlab/), or run it directly.
#
# Settings (environment variables):
#   AUTOGOVERN_API_KEY    required. A Governance API key with the gate:read
#                         scope, issued under Account -> API access & audit.
#                         Keep it in your CI secrets, never in the repository.
#   AUTOGOVERN_SYSTEM_ID  required. The system's ID (ws_...), shown in
#                         Workbench -> AI Registry.
#   AUTOGOVERN_URL        optional. Default https://autogovern.io
#   AUTOGOVERN_MODEL_CARD optional. Path to the model card. Without it the
#                         script looks for MODEL_CARD.md, model_card.md,
#                         MODEL_CARD.json, model-card.md, docs/MODEL_CARD.md
#                         and docs/model_card.md.
#   AUTOGOVERN_REF, AUTOGOVERN_COMMIT optional. Default to the branch and
#                         commit GitHub Actions or GitLab CI provide.
#
# Exit codes: 0 the gate passed; 1 the gate failed, or AutoGovern could not
# be reached (a gate that cannot be checked counts as failed); 2 a setting is
# missing or wrong.

set -u

URL="${AUTOGOVERN_URL:-https://autogovern.io}"
URL="${URL%/}"
KEY="${AUTOGOVERN_API_KEY:-}"
SID="${AUTOGOVERN_SYSTEM_ID:-}"
CARD="${AUTOGOVERN_MODEL_CARD:-}"
REF="${AUTOGOVERN_REF:-${GITHUB_REF_NAME:-${CI_COMMIT_REF_NAME:-}}}"
COMMIT="${AUTOGOVERN_COMMIT:-${GITHUB_SHA:-${CI_COMMIT_SHA:-}}}"

say() { printf '%s\n' "AutoGovern gate: $*" >&2; }

command -v curl >/dev/null 2>&1 || { say "curl is not installed on this runner."; exit 2; }
[ -n "$KEY" ] || { say "AUTOGOVERN_API_KEY is not set. Add it as a CI secret."; exit 2; }
case "$KEY" in
  *[!A-Za-z0-9_-]*) say "AUTOGOVERN_API_KEY has unexpected characters. Paste the key exactly as issued."; exit 2 ;;
esac
case "$SID" in
  ws_*) case "$SID" in *[!a-z0-9_]*) say "AUTOGOVERN_SYSTEM_ID is not a system ID (ws_...)."; exit 2 ;; esac ;;
  *) say "Set AUTOGOVERN_SYSTEM_ID to the system's ID (ws_...)."; exit 2 ;;
esac
# The key is a bearer credential: only send it over HTTPS (plain HTTP only to
# this machine, for testing).
case "$URL" in
  https://*) ;;
  http://localhost|http://localhost:*|http://127.0.0.1|http://127.0.0.1:*) ;;
  *) say "AUTOGOVERN_URL must start with https://"; exit 2 ;;
esac

model_card=missing
if [ -n "$CARD" ]; then
  if [ -s "$CARD" ]; then model_card=present; else say "No model card at $CARD (or it is empty)."; fi
else
  for f in MODEL_CARD.md model_card.md MODEL_CARD.json model-card.md docs/MODEL_CARD.md docs/model_card.md; do
    if [ -s "$f" ]; then model_card=present; CARD="$f"; break; fi
  done
fi
[ "$model_card" = present ] && say "model card: $CARD"

body="$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/autogovern-gate.$$")"
trap 'rm -f "$body"' EXIT
trap 'exit 1' INT TERM
# The key goes to curl on stdin (its config), so it never appears in the
# process list or in the CI log.
code="$(printf 'header = "Authorization: Bearer %s"\n' "$KEY" | curl -sS -K - -G \
  --max-time 30 --retry 2 --retry-delay 3 --proto =https,http \
  -o "$body" -w '%{http_code}' \
  --data-urlencode "format=text" \
  --data-urlencode "model_card=$model_card" \
  --data-urlencode "ref=$REF" \
  --data-urlencode "commit=$COMMIT" \
  "$URL/api/v1/gate/$SID")" || code="000"

if [ "$code" != "200" ]; then
  say "the gate could not be checked (HTTP $code). Treating it as failed."
  [ -s "$body" ] && head -c 2000 "$body" >&2 && printf '\n' >&2
  exit 1
fi
cat "$body"
if head -n 1 "$body" | grep -q ': PASS$'; then exit 0; fi
exit 1
