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

K01_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$K01_DIR/../.." && pwd)"
SQL_DIR="$REPO_ROOT/desc/sql"
FIXTURE_DIR="$REPO_ROOT/deploy/dev/fixture"

export KUBECONFIG=/etc/rancher/k3s/k3s.yaml

domain_dir() {
	case "$1" in
		user) echo users ;;
		*) echo "$1" ;;
	esac
}

psql_exec() {
	local cluster="$1" sql="$2"
	kubectl -n juwan exec -i "${cluster}-1" -c postgres -- psql \
		-v ON_ERROR_STOP=1 -U app -d app <<<"$sql"
}

psql_file() {
	local cluster="$1" file="$2"
	kubectl -n juwan exec -i "${cluster}-1" -c postgres -- psql \
		-v ON_ERROR_STOP=1 -U app -d app < "$file"
}

clusters=()
while IFS= read -r name; do
	clusters+=("$name")
done < <(kubectl -n juwan get cluster -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n')

for cluster in "${clusters[@]}"; do
	domain="${cluster%-db}"
	dir="$(domain_dir "$domain")"
	echo "$cluster"
	kubectl -n juwan wait --for=condition=Ready "cluster.postgresql.cnpg.io/${cluster}" --timeout=300s
	psql_file "$cluster" "$SQL_DIR/common/update_updated_at_column.sql"
	for f in "$SQL_DIR/$dir"/*.sql; do
		[ -f "$f" ] || continue
		echo "  $(basename "$f")"
		psql_file "$cluster" "$f"
	done
	if [ -f "$FIXTURE_DIR/$dir.sql" ]; then
		echo "  $dir.sql"
		psql_file "$cluster" "$FIXTURE_DIR/$dir.sql"
	fi
done

echo
echo "schema + fixture loaded, ${#clusters[@]} clusters"
