#!/bin/bash
# trigger_coreci.sh - Trigger CoreCI pipeline for the pushed branch
# Invoked by .githooks/pre-push
# Gracefully degrades if CoreCI API is unreachable (Gitea webhook is secondary path).

set -uo pipefail

# Source .env if present (provides GITEA_TOKEN)
# Look in repo root, then cwd, then script dir
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
for env_file in "$REPO_ROOT/.env" "$PWD/.env" "./.env"; do
  if [ -f "$env_file" ]; then
    set -a
    # shellcheck disable=SC1090
    . "$env_file"
    set +a
    break
  fi
done

CORECI_URL="${CORECI_URL:-https://git.cloudinit.dev/coreci/coreci}"
GITEA_TOKEN="${GITEA_TOKEN:-}"

if [ -z "$GITEA_TOKEN" ]; then
  echo "  (skip: GITEA_TOKEN not set)"
  exit 0
fi

while read local_ref local_sha remote_ref remote_sha; do
  branch="${remote_ref#refs/heads/}"
  if [ -z "$branch" ] || [ "$branch" = "HEAD" ]; then
    continue
  fi
  echo "→ Triggering CoreCI for branch: $branch (${local_sha:0:7})"
  payload=$(printf '{"repo":"coreci/orca","branch":"%s","ref":"%s"}' "$branch" "$local_sha")
  if command -v curl >/dev/null 2>&1; then
    curl -fsS -X POST "${CORECI_URL}/api/pipeline/run" \
      -H "Authorization: token ${GITEA_TOKEN}" \
      -H "Content-Type: application/json" \
      -d "$payload" >/dev/null 2>&1 \
      && echo "  ✓ CoreCI triggered" \
      || echo "  (CoreCI trigger failed; pipeline may run via webhook)"
  fi
done
