#!/bin/sh
set -eu

usage() {
  echo "usage: $0 <kubeconfig> <context> <evidence-dir> <session-context>" >&2
  exit 2
}

[ "$#" -eq 4 ] || usage

script_dir=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
repo_root=$(git -C "$script_dir" rev-parse --show-toplevel)
source_branch=$(git -C "$repo_root" branch --show-current)
source_commit=$(git -C "$repo_root" rev-parse HEAD)
[ -n "$source_branch" ] || {
  echo "O11Y proof requires a named source branch" >&2
  exit 1
}
[ -z "$(git -C "$repo_root" status --porcelain)" ] || {
  echo "O11Y proof requires a clean source branch" >&2
  exit 1
}
kubeconfig=$1
context=$2
evidence_dir=$3
session_context=$4
namespace=observability
pod=cp9-o11y-gateway-check
platform_evidence=$evidence_dir/o11y-platform-readiness.json
session_name=$(jq -er '.session_name' "$session_context")
target_region=$(jq -er '.target.region' "$session_context")
public_https_url=$(jq -er '.host.remote.public_https_url' "$session_context")
public_host=$(jq -er '.host.remote.public_https_record_name' "$session_context")
public_nlb_url="http://$(jq -er '.host.remote.public_load_balancer_dns' "$session_context")"
private_write_path=/multitenant/api/v1/write
private_write_host=o11y.$public_host
private_write_source=$(jq -er '.host.remote.o11y_endpoint_service_source_cidr' "$session_context")
private_write_allowed_ip=${private_write_source%/32}
[ "$private_write_allowed_ip/32" = "$private_write_source" ] || {
  echo "private write source must be one exact provider NLB IPv4 /32" >&2
  exit 1
}

run_kubectl() {
  KUBECONFIG="$kubeconfig" kubectl --context "$context" "$@"
}

cleanup_gateway_proof() {
  run_kubectl --namespace "$namespace" delete pod "$pod" --ignore-not-found --wait=false >/dev/null 2>&1 || true
  run_kubectl --namespace "$namespace" delete configmap o11y-gateway-check --ignore-not-found >/dev/null 2>&1 || true
}
trap cleanup_gateway_proof EXIT INT TERM

check_public_private_write_absent() {
  label=$1
  url=$2
  response=$(
    curl --silent --show-error --request POST \
      --header "Host: $private_write_host" \
      --header "X-Real-IP: $private_write_allowed_ip" \
      --header "X-Forwarded-For: $private_write_allowed_ip" \
      --write-out '\n%{http_code}' \
      "$url"
  )
  status=$(printf '%s\n' "$response" | tail -n 1)
  [ "$status" = 404 ] || {
    echo "private write route was present through public $label (HTTP $status)" >&2
    exit 1
  }
  printf '%s' "$status"
}

run_kubectl --namespace "$namespace" create configmap o11y-gateway-check \
  --from-file=gateway-checker.py="$script_dir/gateway-checker.py" \
  --from-file=proof_client.py="$script_dir/proof_client.py" \
  --dry-run=client -o yaml |
  run_kubectl --namespace "$namespace" apply -f -

[ -s "$platform_evidence" ] || {
  echo "missing platform readiness evidence: $platform_evidence" >&2
  exit 1
}

vm_account_id=$(jq -er '.vm_account_id' "$platform_evidence")
vm_project_id=$(jq -er '.vm_project_id' "$platform_evidence")
cluster_id=$(jq -er '.cluster_id' "$platform_evidence")
platform_source_commit=$(jq -er '.source.commit' "$platform_evidence")
[ "$platform_source_commit" = "$source_commit" ] || {
  echo "platform proof commit $platform_source_commit does not match current $source_commit" >&2
  exit 1
}

routes_json=$(
  run_kubectl --namespace "$namespace" get httproute \
    cp9-o11y-metrics cp9-o11y-private-write cp9-o11y-private-dedicated-write \
    -o json
)
printf '%s' "$routes_json" |
  jq -e -f "$script_dir/gateway-route-filter.jq" >/dev/null
run_kubectl --namespace "$namespace" get ingress \
  cp9-o11y-global-metadata cp9-o11y-public-read -o json |
  jq -e '
    .items | length == 2 and
    (first(.[] | select(.metadata.name == "cp9-o11y-global-metadata")) |
      .spec.ingressClassName == "kong" and
      .spec.rules[0].http.paths[0].path == "/external" and
      .spec.rules[0].http.paths[0].backend.service.name == "globalserver") and
    (first(.[] | select(.metadata.name == "cp9-o11y-public-read")) |
      .spec.ingressClassName == "kong" and
      .spec.rules[0].http.paths[0].path == "/~/[0-9a-fA-F-]{36}/metrics/api/v1/" and
      .spec.rules[0].http.paths[0].backend.service.name == "o11y-metrics-select" and
      (.metadata.annotations["konghq.com/plugins"] | endswith(",cp9-o11y-public-route")))
  ' >/dev/null
run_kubectl --namespace "$namespace" get kongplugin \
  cp9-o11y-key-auth cp9-o11y-private-write-rewrite cp9-o11y-dedicated-route cp9-o11y-public-route -o json |
  jq -e '
    .items | length == 4 and
    (first(.[] | select(.metadata.name == "cp9-o11y-key-auth")) |
      .metadata.annotations["kubernetes.io/ingress.class"] == "kong") and
    (first(.[] | select(.metadata.name == "cp9-o11y-private-write-rewrite")) |
      .metadata.annotations["kubernetes.io/ingress.class"] == "shared-regional-kong" and
      .plugin == "request-transformer" and
      .config.replace.uri == "/insert/multitenant/prometheus/api/v1/write") and
    (first(.[] | select(.metadata.name == "cp9-o11y-dedicated-route")) |
      .metadata.annotations["kubernetes.io/ingress.class"] == "shared-regional-kong" and
      .plugin == "o11y-dedicated-route") and
    (first(.[] | select(.metadata.name == "cp9-o11y-public-route")) |
      .metadata.annotations["kubernetes.io/ingress.class"] == "kong" and
      .plugin == "o11y-dedicated-route")
  ' >/dev/null
run_kubectl --namespace kong-system get deployment/kong-ingress-controller-kong service/kong-ingress-controller-kong-proxy -o json |
  jq -e '
    .items | length == 2 and
    any(.[]; .kind == "Deployment" and .status.availableReplicas == 1) and
    any(.[]; .kind == "Service")
  ' >/dev/null
run_kubectl --namespace shared-regional-kong-system get \
  deployment/shared-regional-kong-ingress-controller-kong \
  service/shared-regional-kong-ingress-controller-kong-remote-proxy \
  -o json |
  jq -e '
    .items | length == 2 and
    any(.[]; .kind == "Deployment" and .status.availableReplicas == 1) and
    any(
      .[];
      .kind == "Service" and
      .spec.type == "LoadBalancer" and
      .spec.ports == [{name: "proxy", port: 81, protocol: "TCP", targetPort: 8000}]
    )
  ' >/dev/null

run_kubectl --namespace "$namespace" delete pod "$pod" \
  --ignore-not-found --wait=true >/dev/null

VM_ACCOUNT_ID="$vm_account_id" VM_PROJECT_ID="$vm_project_id" CLUSTER_ID="$cluster_id" jq -n \
  --arg pod "$pod" \
  --arg namespace "$namespace" \
    --arg session "$session_name" \
    --arg region "$target_region" \
    --arg public_https_url "$public_https_url" \
  '{
    apiVersion: "v1",
    kind: "Pod",
    metadata: {
      name: $pod,
      namespace: $namespace,
      labels: {
        "app.kubernetes.io/name": "o11y-gateway-check",
        "app.kubernetes.io/part-of": "cp9-o11y"
      }
    },
    spec: {
      restartPolicy: "Never",
      activeDeadlineSeconds: 180,
      containers: [{
        name: "check",
        image: "public.ecr.aws/docker/library/python:3.12-alpine@sha256:6d43704baacd1bfbe7c295d7f13079d5d8104ed33568873133f8fc69980419df",
        command: ["python", "/check/gateway-checker.py"],
        env: [
          {
            name: "PYTHONDONTWRITEBYTECODE",
            value: "1"
          },
          {
            name: "VM_ACCOUNT_ID",
            value: env.VM_ACCOUNT_ID
          },
          {
            name: "VM_PROJECT_ID",
            value: env.VM_PROJECT_ID
          },
          {
            name: "CP9_CLUSTER_ID",
            value: env.CLUSTER_ID
          },
          {
            name: "CP9_SESSION_NAME",
            value: $session
          },
          {
            name: "CP9_TARGET_REGION",
            value: $region
          },
          {
            name: "CP9_PUBLIC_HTTPS_URL",
            value: $public_https_url
          },
          {
            name: "CP9_AUTH0_CLIENT_ID",
            valueFrom: {
              secretKeyRef: {
                name: "cp9-o11y-runtime",
                key: "auth0-client-id"
              }
            }
          },
          {
            name: "CP9_AUTH0_CLIENT_SECRET",
            valueFrom: {
              secretKeyRef: {
                name: "cp9-o11y-runtime",
                key: "auth0-client-secret"
              }
            }
          },
          {
            name: "CP9_METRICS_WRITE_TOKEN",
            valueFrom: {
              secretKeyRef: {
                name: "cp9-o11y-runtime",
                key: "metrics-write-token"
              }
            }
          }
        ],
        volumeMounts: [{
          name: "check",
          mountPath: "/check",
          readOnly: true
        }],
        securityContext: {
          runAsNonRoot: true,
          runAsUser: 65532,
          allowPrivilegeEscalation: false,
          capabilities: {drop: ["ALL"]}
        },
        resources: {
          requests: {cpu: "10m", memory: "32Mi"},
          limits: {cpu: "200m", memory: "128Mi"}
        }
      }],
      volumes: [{
        name: "check",
        configMap: {name: "o11y-gateway-check"}
      }],
      securityContext: {
        seccompProfile: {type: "RuntimeDefault"}
      }
    }
  }' |
  run_kubectl apply -f -

phase=
for _ in $(seq 1 90); do
  phase=$(run_kubectl --namespace "$namespace" get pod "$pod" -o jsonpath='{.status.phase}')
  case "$phase" in
    Succeeded) break ;;
    Failed)
      run_kubectl --namespace "$namespace" logs "$pod" >&2 || true
      echo "O11Y gateway check failed" >&2
      exit 1
      ;;
  esac
  sleep 2
done
[ "$phase" = "Succeeded" ] || {
  run_kubectl --namespace "$namespace" logs "$pod" >&2 || true
  echo "O11Y gateway check did not complete" >&2
  exit 1
}

check_result=$(run_kubectl --namespace "$namespace" logs "$pod")
printf '%s' "$check_result" |
  jq -e '
    .status == "passed" and
    .auth0_status == 200 and
    .global_api_unauth_status == 401 and
    .global_api_wrong_token_status == 401 and
    .global_api_status == 200 and
    .cluster_list_count == 1 and
    .metrics_unauth_status == 401 and
    .metrics_wrong_token_status == 401 and
    (.metrics_unknown_path_status == 404 or .metrics_unknown_path_status == 405) and
    (.metrics_write_status == 200 or .metrics_write_status == 204) and
    .metrics_query_status == 200 and
    .metrics_marker == "cp9_o11y_gateway_ready" and
    .active_clusters_after_delete == 0
  ' >/dev/null

private_write_public_alb_status=$(
  check_public_private_write_absent ALB "$public_https_url$private_write_path"
)
private_write_public_nlb_status=$(
  check_public_private_write_absent NLB "$public_nlb_url$private_write_path"
)

run_kubectl --namespace "$namespace" delete pod "$pod" --wait=true >/dev/null
run_kubectl --namespace "$namespace" delete configmap o11y-gateway-check --ignore-not-found >/dev/null
trap - EXIT INT TERM

mkdir -p "$evidence_dir"
printf '%s' "$check_result" |
  jq \
    --arg namespace "$namespace" \
    --arg globalMetadataRoute "observability/cp9-o11y-global-metadata" \
    --arg publicReadRoute "observability/cp9-o11y-public-read" \
    --arg metricsRoute "observability/cp9-o11y-metrics" \
    --arg privateWriteRoute "observability/cp9-o11y-private-write" \
    --arg privateDedicatedWriteRoute "observability/cp9-o11y-private-dedicated-write" \
    --arg publicHTTPSURL "$public_https_url" \
    --argjson privateWritePublicALBStatus "$private_write_public_alb_status" \
    --argjson privateWritePublicNLBStatus "$private_write_public_nlb_status" \
    --arg sourceBranch "$source_branch" \
    --arg sourceCommit "$source_commit" \
    '. + {
      apiVersion: "cp9.o11y/v1alpha1",
      kind: "O11yGatewayReadiness",
      namespace: $namespace,
      routes: {
        globalMetadata: $globalMetadataRoute,
        publicRead: $publicReadRoute,
        metrics: $metricsRoute,
        privateWrite: $privateWriteRoute,
        privateDedicatedWrite: $privateDedicatedWriteRoute
      },
      publicHTTPSURL: $publicHTTPSURL,
      private_write_public_alb_status: $privateWritePublicALBStatus,
      private_write_public_nlb_status: $privateWritePublicNLBStatus,
      source: {
        branch: $sourceBranch,
        commit: $sourceCommit,
        clean: true
      }
    }' >"$evidence_dir/o11y-gateway-readiness.json"

echo "O11Y gateway readiness passed"
