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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel)"
source "${REPO_ROOT}/deployments/lib/lib.sh"

echo "==> Checking ops-server rollout..."
kubectl -n ops-system rollout status deployment/ops-server --timeout=5m

if [[ -z "${OPS_SERVER_URL:-}" ]]; then
  OPS_SERVER_VALUES_FILE="${OPS_SERVER_VALUES_FILE:?OPS_SERVER_URL or OPS_SERVER_VALUES_FILE is required}"
  OPS_SERVER_URL="$(resolve_ops_server_url "${OPS_SERVER_VALUES_FILE}")"
fi
if [[ -z "${OPS_SERVER_URL}" ]]; then
  echo "OPS_SERVER_URL could not be resolved" >&2
  exit 1
fi

echo "==> Checking ops-server health endpoint..."
curl -fsS "${OPS_SERVER_URL%/}/health"

echo "==> Checking ops-server HelmRelease readiness..."
kubectl -n ops-system wait --for=condition=Ready helmrelease/ops-server --timeout=5m

echo "==> Checking legacy o11y-crds HelmRelease is gone..."
if kubectl -n ops-system get helmrelease o11y-crds >/dev/null 2>&1; then
  echo "ERROR: legacy HelmRelease o11y-crds is still present" >&2
  exit 1
fi

echo "==> Checking infra HelmReleases managed through ops-server..."
for hr in ops-server self-monitoring self-vector cert-manager; do
  echo "==> Checking HelmRelease ${hr}"
  kubectl -n ops-system get helmrelease "${hr}" >/dev/null
  kubectl -n ops-system wait --for=condition=Ready "helmrelease/${hr}" --timeout=5m
done

echo "==> All ops-server bootstrap checks passed."
