#!/bin/bash
set -euo pipefail

ENV_FILE="/opt/flight-manager/development/.env"
TEMPLATE="/opt/flight-manager/development/config.template.json"
OUTPUT="/opt/flight-manager/development/config.generated.json"
DOCKER_COMPOSE_PATH="/opt/stacks/..."

echo "[deploy] Secrets changed, reloading..."

# Load new secrets
set -a; source "$ENV_FILE"; set +a

# Validate all required vars are present
REQUIRED_VARS=$(grep -o '\${[A-Z0-9_]\+}' "$TEMPLATE" | tr -d '${}' | sort -u)
MISSING=()
for var in $REQUIRED_VARS; do
  [ -z "${!var+set}" ] && MISSING+=("$var")
done
if [ ${#MISSING[@]} -gt 0 ]; then
  echo "[deploy] ERROR: Missing variables: ${MISSING[*]}"
  exit 1
fi

# Render config.generated.json
VARS=$(printf '${%s} ' $REQUIRED_VARS)
envsubst "$VARS" < "$TEMPLATE" > "$OUTPUT"

# Validate JSON
if ! jq empty "$OUTPUT" 2>/dev/null; then
  echo "[deploy] ERROR: Generated config is not valid JSON"
  rm -f "$OUTPUT"
  exit 1
fi

echo "[deploy] Config generated at $OUTPUT"

# Restart docker compose
docker compose -f "$DOCKER_COMPOSE_PATH" restart

echo "[deploy] Done."
