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

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

rule_files=()
while IFS= read -r file; do
  rule_files+=("$file")
done < <(find \
  "$repo_root/docker/ory/oathkeeper" \
  "$repo_root/config/.generated/ory/oathkeeper" \
  -maxdepth 1 -name 'rules*.json' -print | sort)

for file in "${rule_files[@]}"; do
  if grep -Eq '"id"[[:space:]]*:[[:space:]]*"kratos-public"' "$file"; then
    echo "ERROR: $file must not define a public Kratos proxy rule." >&2
    failures=$((failures + 1))
  fi
  if grep -Eq '"url"[[:space:]]*:[[:space:]]*"[^"]*/kratos/<\.\*>"' "$file"; then
    echo "ERROR: $file must not expose Kratos under /kratos." >&2
    failures=$((failures + 1))
  fi
  if grep -Eq '"url"[[:space:]]*:[[:space:]]*"http://kratos:4433"' "$file"; then
    echo "ERROR: $file must not proxy public requests directly to kratos:4433." >&2
    failures=$((failures + 1))
  fi
done

for compose_file in \
  "$repo_root/compose.ory.yaml" \
  "$repo_root/docker/compose.ory.yaml" \
  "$repo_root/docker/staging_pull_compose.template.yaml" \
  "$repo_root/deploy/templates/docker-compose.yaml"
do
  kratos_block="$(
    awk '
      /^[[:space:]]+kratos:/ { in_block=1; print; next }
      in_block && /^[[:space:]]+[A-Za-z0-9_-]+:/ { exit }
      in_block { print }
    ' "$compose_file"
  )"
  if grep -Eq '^[[:space:]]+ports:' <<<"$kratos_block"; then
    echo "ERROR: $compose_file must not publish Kratos ports directly." >&2
    failures=$((failures + 1))
  fi
done

if [[ "$failures" -gt 0 ]]; then
  exit 1
fi

echo "OK: Kratos public API is not exposed through Oathkeeper rules or compose ports."
