#!/usr/bin/env bash
# Write deploy/calendar-api-port.conf from node/.env PORT (reference only — not loaded by Apache).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=lib/node-env-port.sh
source "$ROOT/scripts/lib/node-env-port.sh"

REPO_CONF="$ROOT/deploy/calendar-api-port.conf"
INSTALL=0

for arg in "$@"; do
  case "$arg" in
    --install) INSTALL=1 ;;
    -h|--help)
      echo "Usage: bash scripts/sync-apache-api-port.sh [--install]"
      echo "  Writes deploy/calendar-api-port.conf from node/.env PORT (reference only)."
      exit 0
      ;;
    *)
      echo "Unknown option: $arg" >&2
      exit 1
      ;;
  esac
done

CALENDAR_API_PORT="$(node_env_port "$ROOT")"

cat > "$REPO_CONF" <<EOF
# Reference only — Apache uses Define CALENDAR_API in calendar.gventure.info-le-ssl.conf
# Source of truth: node/.env PORT=$CALENDAR_API_PORT
Define CALENDAR_API http://127.0.0.1:${CALENDAR_API_PORT}
EOF
printf 'Wrote %s from node/.env PORT=%s\n' "$REPO_CONF" "$CALENDAR_API_PORT"

if [[ "$INSTALL" -ne 1 ]]; then
  printf '\nApache port is configured via: sudo bash scripts/configure-apache.sh\n'
  exit 0
fi

echo "Note: --install is deprecated. Use: sudo bash scripts/configure-apache.sh" >&2
exit 0
