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

# Usa properties.env nella directory corrente, oppure un path passato come primo argomento.
PROPERTIES_FILE="${1:-properties.env}"

if [[ ! -f "$PROPERTIES_FILE" ]]; then
  echo "Errore: file non trovato: $PROPERTIES_FILE" >&2
  exit 1
fi

# 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:]]*//')"

# 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" >&2
  exit 1
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

# Esegue lo script richiesto con la stringa costruita
/root/work/pipeline/add-listener.sh "$endpoint https-$token $token-secret"
