#!/bin/bash
helm repo update cilium

# Wait for Kubernetes API to be ready
echo "Waiting for Kubernetes API to be available..."
until kubectl get namespace >/dev/null 2>&1; do 
  echo "Waiting for API server..."
  sleep 5
done
echo "API server is ready"

# Install Prometheus CRDs before Cilium (required for ServiceMonitors)
echo "Installing Prometheus CRDs..."
curl -sL https://github.com/prometheus-operator/prometheus-operator/releases/latest/download/stripped-down-crds.yaml | kubectl apply -f -

# Wait for Prometheus CRDs to be established
echo "Waiting for Prometheus CRDs to be established..."
kubectl wait --for=condition=Established --timeout=60s crd/servicemonitors.monitoring.coreos.com
if [ $? -ne 0 ]; then
  echo "Prometheus CRDs failed to establish. Continuing anyway..."
fi

# Install Cilium EE:
echo "Installing Cilium..."
helm upgrade -i cilium cilium/cilium \
  --wait \
  --version 1.18.1 \
  --namespace kube-system \
  -f ../helm-values/cilium-values.yaml

# Wait for the Cilium CRDs to be available.
kubectl rollout status -n kube-system deployment cilium-operator --timeout=180s
sleep 10
kubectl wait --for condition=established --timeout=60s crd/ciliumclusterwidenetworkpolicies.cilium.io
if [ $? -ne 0 ]; then
  echo "Cilium CRDs are not available. Check Cilium installation (especially the Cilium Operator pod)."
  exit 1
fi
sleep 10

# Activate DNS visibility without blocking any other traffic:
kubectl apply -f ../manifests/ccnp-dns-visibility.yaml

# Nginx Ingress
helm upgrade -i nginx ingress-nginx/ingress-nginx \
  --version 4.13.1 \
  --namespace ingress-nginx \
  --create-namespace \
  -f ../helm-values/nginx-ingress-values.yaml

# Prometheus Stack
helm upgrade -i prometheus prometheus-community/kube-prometheus-stack \
  --version 69.8.2 \
  --namespace monitoring \
  --create-namespace \
  -f ../helm-values/kube-prometheus-stack-values.yaml

# Deploy Echo Demo App
kubectl apply -f ../manifests/echo-server.yaml
kubectl apply -f ../manifests/echo-client.yaml

# Deploy Goldpinger
kubectl apply -f ../manifests/goldpinger.yaml
