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

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

apply_docs() {
	local file="$1" kind="$2" wait_expr="$3" buf i
	i=0
	buf=""
	while IFS= read -r line; do
		if [[ "$line" == "---" ]]; then
			printf '%s\n' "$buf" | kubectl apply -f -
			i=$((i+1))
			echo "  ($i) applied"
			buf=""
		else
			[[ -n "$buf" ]] && buf+=$'\n'
			buf+="$line"
		fi
	done < "$file"
	printf '%s\n' "$buf" | kubectl apply -f -
	i=$((i+1))
	echo "  ($i) applied"

	if [ -n "$kind" ]; then
		kubectl -n juwan wait --for="$wait_expr" --timeout=900s "$kind" --all || true
	fi
}

echo envoy + ratelimit
kubectl apply -f "${INFRA_DIR}/envoy.yaml"
kubectl apply -f "${INFRA_DIR}/ratelimit.yaml"
kubectl -n juwan wait --for=condition=Ready pod -l app=envoy-gateway --timeout=120s || true
kubectl -n juwan wait --for=condition=Ready pod -l "app in (ratelimit,rl-redis)" --timeout=120s || true

echo redis
apply_docs "${INFRA_DIR}/redis.yaml" "" ""
kubectl -n juwan wait --for=condition=Ready pod -l redis_setup_type=replication --timeout=600s || true

echo postgres
apply_docs "${INFRA_DIR}/postgres.yaml" cluster.postgresql.cnpg.io "condition=Ready"

echo mongo
kubectl apply -f "${INFRA_DIR}/mongo.yaml"
kubectl -n juwan wait --for=jsonpath='{.status.phase}'=Running mongodbcommunity/chat-mongodb --timeout=600s || true

echo kafka
kubectl apply -f "${INFRA_DIR}/kafka.yaml"
kubectl -n redpanda wait --for=condition=Ready redpanda/juwan-kafka --timeout=900s || true

kubectl get pods -A
