#!/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"
	local pw
	pw="$(kubectl -n juwan get secret "${cluster}-app" -o jsonpath='{.data.password}' | base64 -d)"
	kubectl -n juwan exec -i "${cluster}-1" -c postgres -- env PGPASSWORD="$pw" \
		psql -v ON_ERROR_STOP=1 -h 127.0.0.1 -U app -d app <<<"$sql"
}

psql_file() {
	local cluster="$1" file="$2"
	local pw
	pw="$(kubectl -n juwan get secret "${cluster}-app" -o jsonpath='{.data.password}' | base64 -d)"
	kubectl -n juwan exec -i "${cluster}-1" -c postgres -- env PGPASSWORD="$pw" \
		psql -v ON_ERROR_STOP=1 -h 127.0.0.1 -U app -d app < "$file"
}

kubectl -n juwan wait --for=condition=Ready cluster.postgresql.cnpg.io --all --timeout=600s

clusters=()
while IFS= read -r name; do
	[ -n "$name" ] && clusters+=("$name")
done < <(kubectl -n juwan get cluster -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')

for cluster in "${clusters[@]}"; do
	domain="${cluster%-db}"
	dir="$(domain_dir "$domain")"
	echo "$cluster"
	psql_exec "$cluster" "DROP OWNED BY app CASCADE;"
	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"
