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

# Uso: ./addlistener.sh [env] [properties_file]
# env e' ignorato: endpoint viene sempre letto dalla chiave "endpoint".
ENVIRONMENT="${1:-dev}"
PROPERTIES_FILE="${2:-env/${ENVIRONMENT}/values.env}"
# Hardening per evitare errori con set -u in esecuzioni/sourcing anomali
: "${PROPERTIES_FILE:=env/${ENVIRONMENT}/values.env}"
ENV_DIR="env/${ENVIRONMENT}"

if [[ -n "$ENVIRONMENT" ]]; then
  echo "Ambiente richiesto: $ENVIRONMENT (chiave usata: endpoint)"
fi

if [[ -f "${PROPERTIES_FILE:-}" ]]; then
  # Estrae endpoint ignorando commenti e spazi, supportando anche endpoint = valore
  endpoint_raw="$({ grep -E '^[[:space:]]*endpoint[[:space:]]*=' "${PROPERTIES_FILE}" | tail -n1 || true; } | sed -E 's/^[[:space:]]*endpoint[[:space:]]*=[[:space:]]*//')"
elif [[ -d "$ENV_DIR" ]]; then
  # Estrae endpoint da qualsiasi file .env nella directory dell'ambiente
  endpoint_raw="$({ grep -r '^[[:space:]]*endpoint[[:space:]]*=' "$ENV_DIR" 2>/dev/null | head -n1 || true; } | sed -E 's/^[^:]*:[[:space:]]*endpoint[[:space:]]*=[[:space:]]*//')"
else
  echo "Warning: file non trovato: ${PROPERTIES_FILE:-<non impostato>} e directory non trovata: $ENV_DIR" >&2
  exit 0
fi

# Rimuove eventuali virgolette e spazi ai bordi
endpoint="$(echo "$endpoint_raw" | sed -E 's/^[[:space:]"\x27]+//; s/[[:space:]"\x27]+$//')"

if [[ -z "$endpoint" ]]; then
  echo "La chiave endpoint non e valorizzata in ${PROPERTIES_FILE:-<non impostato>}" >&2
  exit 0
fi

# Per calcolare il token usa host pulito (senza schema e path)
host_for_token="${endpoint#*://}"
host_for_token="${host_for_token%%/*}"
token="${host_for_token%%.*}"

if [[ -z "$token" ]]; then
  echo "Impossibile estrarre il token da endpoint: $endpoint" >&2
  exit 1
fi

# Output richiesto: <endpoint> https-<token> <token>-secret
/root/work/pipeline/add-listener.sh $endpoint https-$token $token-secret
