#!/bin/bash
# Aggiunge un listener HTTPS direttamente sulla risorsa K8s Gateway
# main-gateway nel namespace nginx-gateway, tramite kubectl patch.
#
# Uso:
#   ./add-listener.sh <hostname> <name> <secret-name>
#
# Esempio:
#   ./add-listener.sh sonarqube.italiadatacenter.com https-sonarqube sonarqube-secret

set -euo pipefail

GATEWAY_NAME="main-gateway"
GATEWAY_NS="nginx-gateway"
DNS_API_BASE="http://10.20.1.10:5380/api/zones/records/add"
DNS_API_TOKEN="fb85a1eaa5216eeefda11c0e500cfeb8cfaa1ddda9eaae0781e656eaf52852a6"
DNS_ZONE="italiadatacenter.com"
DNS_IP="10.20.1.100"
DNS_TTL="3600"

HOSTNAME_VAL="${1:-}"
NAME_VAL="${2:-}"
SECRET_NAME="${3:-}"

if [[ -z "$HOSTNAME_VAL" || -z "$NAME_VAL" || -z "$SECRET_NAME" ]]; then
  echo "Uso: $0 <hostname> <name> <secret-name>"
  echo "Es.: $0 sonarqube.italiadatacenter.com https-sonarqube sonarqube-secret"
  exit 1
fi

# Controlla idempotenza: verifica se il listener esiste già per nome o hostname
EXISTING_NAME=$(kubectl get gateway "$GATEWAY_NAME" -n "$GATEWAY_NS" \
  -o jsonpath='{.spec.listeners[?(@.name=="'"${NAME_VAL}"'")].name}')

if [[ -n "$EXISTING_NAME" ]]; then
  echo "Attenzione: listener con name '${NAME_VAL}' già presente. Nessuna modifica."
  exit 0
fi

EXISTING_HOST=$(kubectl get gateway "$GATEWAY_NAME" -n "$GATEWAY_NS" \
  -o jsonpath='{.spec.listeners[?(@.hostname=="'"${HOSTNAME_VAL}"'")].hostname}')

if [[ -n "$EXISTING_HOST" ]]; then
  echo "Attenzione: listener con hostname '${HOSTNAME_VAL}' già presente. Nessuna modifica."
  exit 0
fi

# JSON Patch: aggiunge il nuovo listener in append alla lista
PATCH=$(cat <<EOF
[{
  "op": "add",
  "path": "/spec/listeners/-",
  "value": {
    "allowedRoutes": {
      "namespaces": {
        "from": "All"
      }
    },
    "hostname": "${HOSTNAME_VAL}",
    "name": "${NAME_VAL}",
    "port": 443,
    "protocol": "HTTPS",
    "tls": {
      "certificateRefs": [
        {
          "group": "",
          "kind": "Secret",
          "name": "${SECRET_NAME}"
        }
      ],
      "mode": "Terminate"
    }
  }
}]
EOF
)

kubectl patch gateway "$GATEWAY_NAME" \
  -n "$GATEWAY_NS" \
  --type=json \
  -p "$PATCH"

echo "Listener aggiunto alla risorsa ${GATEWAY_NS}/${GATEWAY_NAME}:"
echo "  hostname : ${HOSTNAME_VAL}"
echo "  name     : ${NAME_VAL}"
echo "  secret   : ${SECRET_NAME}"

# Se l'hostname e' del tipo <server>.italiadatacenter.com, registra/aggiorna il record A via API DNS.
if [[ "$HOSTNAME_VAL" =~ ^[a-zA-Z0-9-]+\.italiadatacenter\.com$ ]]; then
  echo "Hostname conforme al dominio ${DNS_ZONE}. Aggiorno il record DNS..."
  curl --fail --silent --show-error \
    -H "Authorization: Bearer ${DNS_API_TOKEN}" \
    -X GET "${DNS_API_BASE}?domain=${HOSTNAME_VAL}&zone=${DNS_ZONE}&type=A&ipAddress=${DNS_IP}&ttl=${DNS_TTL}&overwrite=true"
  echo "Record DNS creato/aggiornato: ${HOSTNAME_VAL} -> ${DNS_IP}"
else
  echo "Hostname fuori formato <server>.${DNS_ZONE}: salto creazione record DNS"
fi
