#!/bin/sh
# Migration 37 --> 38
# Update PostgreSQL image to 17.7-standard-trixie for system databases.
#
# This migration updates the imageName for all CNPG clusters with names matching
# system database patterns (keycloak-db, harbor-db, grafana-db, alerta-db, seaweedfs-db)
# to use the pinned PostgreSQL 17.7-standard-trixie image from ghcr.io/cloudnative-pg.
#
# NOTE: This migration ONLY updates system CNPG Cluster resources (clusters.postgresql.cnpg.io),
# NOT user-created Postgres applications (postgreses.apps.cozystack.io).

set -euo pipefail

TARGET_IMAGE="ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie"

# Database names to update (can be in any namespace)
DB_NAMES="keycloak-db harbor-db grafana-db alerta-db seaweedfs-db"

echo "=== Updating PostgreSQL images for system databases: $DB_NAMES ==="
echo "Target image: $TARGET_IMAGE"

# Find all CNPG clusters across all namespaces
ALL_CLUSTERS=$(kubectl get clusters.postgresql.cnpg.io -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}' 2>/dev/null || true)

for entry in $ALL_CLUSTERS; do
  [ -z "$entry" ] && continue

  NAMESPACE="${entry%%/*}"
  CLUSTER_NAME="${entry##*/}"

  # Skip if this is a user-created Postgres (has apps.cozystack.io/application.name label)
  APP_LABEL=$(kubectl get clusters.postgresql.cnpg.io -n "$NAMESPACE" "$CLUSTER_NAME" \
    -o jsonpath='{.metadata.labels.apps\.cozystack\.io/application\.name}' 2>/dev/null || echo "")
  if [ -n "$APP_LABEL" ]; then
    continue
  fi

  # Check if cluster name matches one of our target databases
  MATCH=false
  for db_name in $DB_NAMES; do
    if [ "$CLUSTER_NAME" = "$db_name" ]; then
      MATCH=true
      break
    fi
  done

  if [ "$MATCH" = false ]; then
    continue
  fi

  # Get current imageName
  CURRENT_IMAGE=$(kubectl get clusters.postgresql.cnpg.io -n "$NAMESPACE" "$CLUSTER_NAME" \
    -o jsonpath='{.spec.imageName}' 2>/dev/null || echo "")

  if [ "$CURRENT_IMAGE" = "$TARGET_IMAGE" ]; then
    echo "SKIP $NAMESPACE/$CLUSTER_NAME: already using $TARGET_IMAGE"
    continue
  fi

  echo "PATCH $NAMESPACE/$CLUSTER_NAME: $CURRENT_IMAGE -> $TARGET_IMAGE"

  kubectl patch clusters.postgresql.cnpg.io -n "$NAMESPACE" "$CLUSTER_NAME" \
    --type=merge \
    --patch "{\"spec\":{\"imageName\":\"${TARGET_IMAGE}\"}}"
done

echo "=== PostgreSQL image update completed ==="

# Stamp version
kubectl create configmap -n cozy-system cozystack-version \
  --from-literal=version=38 --dry-run=client -o yaml | kubectl apply -f-
