#!/usr/bin/env bash
# Unisce infra/.env.production.example in infra/.env senza sovrascrivere valori già impostati.
# Uso locale:  ./scripts/merge_production_env.sh
# Sul server:  REMOTE=1 ./scripts/merge_production_env.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
EXAMPLE="$ROOT/infra/.env.production.example"
REMOTE="${REMOTE:-0}"
SERVER="${DEPLOY_SERVER:-eminux@192.168.1.146}"
ENV_PATH="${ENV_PATH:-/opt/matchlivetv/infra/.env}"

if [[ "$REMOTE" == "1" ]]; then
  scp "$EXAMPLE" "$SERVER:/tmp/matchlivetv-env.example"
  ssh "$SERVER" "REMOTE_ENV='$ENV_PATH' bash -s" <<'REMOTE'
set -euo pipefail
EXAMPLE=/tmp/matchlivetv-env.example
ENV="${REMOTE_ENV}"
touch "$ENV"
while IFS= read -r line || [[ -n "$line" ]]; do
  [[ "$line" =~ ^[[:space:]]*# ]] && continue
  [[ "$line" =~ ^[[:space:]]*$ ]] && continue
  key="${line%%=*}"
  [[ "$key" == "$line" ]] && continue
  if ! grep -q "^${key}=" "$ENV" 2>/dev/null; then
    echo "$line" >> "$ENV"
    echo "  + aggiunto: $key"
  fi
done < "$EXAMPLE"
echo ""
echo "File: $ENV ($(wc -l < "$ENV") righe)"
echo "Chiavi presenti:"
grep -E '^[A-Z_]+=' "$ENV" | cut -d= -f1 | sort
echo ""
echo "Chiavi VUOTE (da compilare):"
grep -E '^[A-Z_]+=$' "$ENV" | cut -d= -f1 || echo "  (nessuna)"
REMOTE
  exit 0
fi

ENV="${ENV_FILE:-$ROOT/infra/.env}"
touch "$ENV"
while IFS= read -r line || [[ -n "$line" ]]; do
  [[ "$line" =~ ^[[:space:]]*# ]] && continue
  [[ "$line" =~ ^[[:space:]]*$ ]] && continue
  key="${line%%=*}"
  [[ "$key" == "$line" ]] && continue
  if ! grep -q "^${key}=" "$ENV" 2>/dev/null; then
    echo "$line" >> "$ENV"
    echo "  + aggiunto: $key"
  fi
done < "$EXAMPLE"
echo "Fatto: $ENV"
