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

require_container() {
  local name="$1"
  if ! docker inspect "$name" >/dev/null 2>&1; then
    echo "ERROR: required container is missing: $name" >&2
    exit 1
  fi
}

for container in ory_oathkeeper ory_vector ory_clickhouse baron_backend; do
  require_container "$container"
done

vector_state="$(docker inspect -f '{{.State.Status}}' ory_vector)"
if [[ "$vector_state" != "running" ]]; then
  echo "ERROR: ory_vector must be running, got: $vector_state" >&2
  docker logs --tail 100 ory_vector >&2 || true
  exit 1
fi

before_lines="$(docker exec ory_oathkeeper sh -lc 'test -f /var/log/oathkeeper/access.log && wc -l < /var/log/oathkeeper/access.log || echo 0')"
before_rows="$(docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "SELECT count() FROM ory.oathkeeper_access_logs")"

docker run --rm --network public_net curlimages/curl:8.10.1 \
  -fsS http://ory_oathkeeper:4455/health >/dev/null

deadline=$((SECONDS + 20))
after_lines="$before_lines"
while (( SECONDS < deadline )); do
  after_lines="$(docker exec ory_oathkeeper sh -lc 'test -f /var/log/oathkeeper/access.log && wc -l < /var/log/oathkeeper/access.log || echo 0')"
  if (( after_lines > before_lines )); then
    break
  fi
  sleep 1
done

if (( after_lines <= before_lines )); then
  echo "ERROR: Oathkeeper access log did not grow after a proxied request." >&2
  docker exec ory_oathkeeper sh -lc 'ls -l /var/log/oathkeeper && tail -n 50 /var/log/oathkeeper/access.log 2>/dev/null || true' >&2
  exit 1
fi

deadline=$((SECONDS + 30))
after_rows="$before_rows"
while (( SECONDS < deadline )); do
  after_rows="$(docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "SELECT count() FROM ory.oathkeeper_access_logs")"
  if (( after_rows > before_rows )); then
    break
  fi
  sleep 2
done

if (( after_rows <= before_rows )); then
  echo "ERROR: Vector did not insert the new Oathkeeper access log into ClickHouse." >&2
  echo "before_rows=$before_rows after_rows=$after_rows" >&2
  docker logs --tail 100 ory_vector >&2 || true
  exit 1
fi

before_auth_ts="$(docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "SELECT now64(3)")"
auth_status="$(docker run --rm --network public_net curlimages/curl:8.10.1 \
  -sS -o /dev/null -w '%{http_code}' \
  'http://ory_oathkeeper:4455/oauth2/auth?client_id=orgfront&redirect_uri=http%3A%2F%2Flocalhost%3A5175%2Fauth%2Fcallback&response_type=code&scope=openid&state=access-log-e2e&code_challenge=accessloge2e&code_challenge_method=S256')"

if [[ "$auth_status" != "302" ]]; then
  echo "ERROR: expected Oathkeeper OIDC auth request to return 302, got: $auth_status" >&2
  exit 1
fi

deadline=$((SECONDS + 30))
completed_rows=0
granted_rows=0
while (( SECONDS < deadline )); do
  completed_rows="$(docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "
    SELECT count()
    FROM ory.oathkeeper_access_logs
    WHERE timestamp >= toDateTime64('$before_auth_ts', 3)
      AND method = 'GET'
      AND path = '/oauth2/auth'
      AND status = 302
  ")"
  granted_rows="$(docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "
    SELECT count()
    FROM ory.oathkeeper_access_logs
    WHERE timestamp >= toDateTime64('$before_auth_ts', 3)
      AND method = 'GET'
      AND path = '/oauth2/auth'
      AND client_id = 'orgfront'
      AND decision = 'granted'
  ")"
  if (( completed_rows > 0 && granted_rows > 0 )); then
    break
  fi
  sleep 2
done

if (( completed_rows <= 0 )); then
  echo "ERROR: Oathkeeper completed request log did not preserve method/path/status." >&2
  docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "
    SELECT timestamp, method, path, status, client_id, decision
    FROM ory.oathkeeper_access_logs
    WHERE timestamp >= toDateTime64('$before_auth_ts', 3)
    ORDER BY timestamp DESC
    LIMIT 20
    FORMAT Vertical
  " >&2 || true
  exit 1
fi

if (( granted_rows <= 0 )); then
  echo "ERROR: Oathkeeper granted request log did not preserve client_id." >&2
  docker exec ory_clickhouse clickhouse-client --user "${ORY_CLICKHOUSE_USER:-ory}" --password "${ORY_CLICKHOUSE_PASSWORD:-orypass}" --query "
    SELECT timestamp, method, path, status, client_id, decision
    FROM ory.oathkeeper_access_logs
    WHERE timestamp >= toDateTime64('$before_auth_ts', 3)
    ORDER BY timestamp DESC
    LIMIT 20
    FORMAT Vertical
  " >&2 || true
  exit 1
fi
