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

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

"$repo_root/scripts/render_ory_config.sh" >/dev/null

docker run --rm \
  -e ORY_CLICKHOUSE_USER=ory \
  -e ORY_CLICKHOUSE_PASSWORD=orypass \
  -v "$repo_root/docker/ory/vector:/etc/vector:ro" \
  timberio/vector:0.36.0-alpine validate --no-environment /etc/vector/vector.toml >/dev/null

if grep -q '/etc/config/oathkeeper/rules.active.json' "$repo_root/docker/ory/oathkeeper/entrypoint.sh"; then
  echo "ERROR: Oathkeeper entrypoint must not write active rules into the bind-mounted config directory." >&2
  exit 1
fi

if ! grep -q 'file:///tmp/oathkeeper/rules.active.json' "$repo_root/config/.generated/ory/oathkeeper/oathkeeper.yml"; then
  echo "ERROR: Oathkeeper config must load active rules from writable runtime storage." >&2
  exit 1
fi

if ! grep -q '^version: v26.2.0$' "$repo_root/config/.generated/ory/kratos/kratos.yml"; then
  echo "ERROR: Kratos config version must match the v26.2.0 runtime." >&2
  exit 1
fi

cookie_secret="$(grep -E '^COOKIE_SECRET=' "$repo_root/.env" | cut -d= -f2-)"
if [[ ${#cookie_secret} -ne 32 ]]; then
  echo "ERROR: COOKIE_SECRET must be exactly 32 bytes/chars for backend encryptcookie." >&2
  exit 1
fi

root_config="$(
  docker compose --env-file "$repo_root/.env" -f "$repo_root/compose.ory.yaml" config
)"
if ! grep -q "oathkeeper_logs_init:" <<<"$root_config"; then
  echo "ERROR: compose.ory.yaml must initialize the Oathkeeper log volume permissions." >&2
  exit 1
fi
