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

K01_DIR="$(cd "$(dirname "$0")" && pwd)"
export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}"

echo services
for f in "${K01_DIR}/services/"*.yaml; do
	kubectl delete -f "$f" --ignore-not-found --wait=false
done

echo data crs
kubectl -n juwan delete cluster.postgresql.cnpg.io --all --wait=false 2>/dev/null || true
kubectl -n juwan delete redisreplication --all --wait=false 2>/dev/null || true
kubectl -n juwan delete redissentinel --all --wait=false 2>/dev/null || true
kubectl -n juwan delete mongodbcommunity --all --wait=false 2>/dev/null || true
kubectl -n redpanda delete topic --all --wait=false 2>/dev/null || true
kubectl -n redpanda delete redpanda --all --wait=false 2>/dev/null || true

echo network
kubectl delete -f "${K01_DIR}/infra/envoy.yaml" --ignore-not-found --wait=false
kubectl delete -f "${K01_DIR}/infra/ratelimit.yaml" --ignore-not-found --wait=false

sleep 30

echo cleanup orphaned
kubectl -n juwan delete pod --all --force --grace-period=0 2>/dev/null || true
kubectl -n juwan delete pvc --all --wait=false 2>/dev/null || true
kubectl -n redpanda delete pvc -l app.kubernetes.io/instance=juwan-kafka --wait=false 2>/dev/null || true

kubectl get pods,pvc -n juwan
kubectl get pods,pvc -n redpanda
kubectl describe node | grep -A 6 Allocated
