#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if ! command -v opa >/dev/null 2>&1; then
  echo "opa not found. Install OPA: https://www.openpolicyagent.org/docs/latest/#1-download-opa" >&2
  exit 1
fi

opa run --server --addr :8181 ./policies &
OPA_PID=$!
cleanup() {
  kill "${OPA_PID}" >/dev/null 2>&1 || true
}
trap cleanup EXIT

sleep 0.3
export HTTP_ADDR="${HTTP_ADDR:-:8080}"
export OPA_URL="${OPA_URL:-http://localhost:8181}"
export OPA_DECISION_PATH="${OPA_DECISION_PATH:-acp/decision}"
export POLICIES_DIR="${POLICIES_DIR:-$ROOT/policies}"
exec go run ./cmd/server
