#!/bin/bash
set -euo pipefail

# Esegue kubectl apply per ogni sottodirectory di kubernetes separatamente

ENVIRONMENT="${1:-dev}"

YAML_DIR="kubernetes"

# ---------------------------------------------------------------------------
# Cerca risorse postgresql.cnpg.io/v1 nei manifest e deploya una ConfigMap
# ---------------------------------------------------------------------------
CNPG_FILE=$(grep -rl "postgresql.cnpg.io/v1" "$YAML_DIR" 2>/dev/null | head -1 || true)

if [ -n "$CNPG_FILE" ]; then
  echo "Trovata risorsa postgresql.cnpg.io/v1 in: $CNPG_FILE"

  # Estrae metadata.name dal manifest CNPG preferendo yq, altrimenti awk
  if command -v yq >/dev/null 2>&1; then
    PG_NAME=$(yq eval 'select(.apiVersion == "postgresql.cnpg.io/v1") | .metadata.name' "$CNPG_FILE")
  else
    PG_NAME=$(awk '/postgresql\.cnpg\.io\/v1/{found=1} found && /^metadata:/{meta=1} meta && /^\s+name:/{print $2; exit}' "$CNPG_FILE")
  fi

  # Ricava il namespace dal Role namespace-deployer presente nel cluster
  PG_NS=$(kubectl --kubeconfig=./kubeconfig get role namespace-deployer \
     --no-headers \
    -o custom-columns='NS:.metadata.namespace' 2>/dev/null | head -1 || true)
  #PG_NS="${PG_NS:-default}"

  if [ -z "$PG_NAME" ]; then
    echo "⚠️  Impossibile estrarre metadata.name dal cluster CNPG, skip ConfigMap." >&2
  else
    echo "  → cluster: $PG_NAME  namespace: $PG_NS"
    kubectl --kubeconfig=./kubeconfig apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: service-config
  namespace: ${PG_NS}
data:
  tipodb: "postgres"
  urldb: "${PG_NAME}.${PG_NS}.svc.cluster.local"
EOF
    echo "ConfigMap db-config deployata in namespace ${PG_NS}."
  fi
fi

# ---------------------------------------------------------------------------
# Deploy di tutti i manifest Kubernetes
# ---------------------------------------------------------------------------
find "$YAML_DIR" -type d | while read DIR; do
  if ls "$DIR"/*.yaml 1> /dev/null 2>&1; then
    echo "Deploy delle risorse nella directory $DIR..."
    kubectl --kubeconfig=./kubeconfig apply -f "$DIR"
  fi
done

echo "Deploy completato di tutte le directory YAML."

echo "Eseguo check su endpoint da pubblicare"
/root/work/pipeline/addlistener.sh "$ENVIRONMENT"
