#!/bin/bash
# generate-nginx-block.sh
# Generates nginx location block for a CLI site
#
# Usage: ./generate-nginx-block.sh <site-name> [output-file]
#
# Reads port from ports.json and generates nginx config
# Output: stdout or specified file

set -e

# Source centralized config
SCRIPT_DIR_GEN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR_GEN/../../scripts/config.sh"

SITE_NAME=$1
OUTPUT_FILE=$2

if [ -z "$SITE_NAME" ]; then
  echo "Usage: $0 <site-name> [output-file]"
  echo ""
  echo "Examples:"
  echo "  $0 silicon-bali                           # Print to stdout"
  echo "  $0 silicon-bali nginx-blocks/$SITE_NAME.conf  # Save to file"
  exit 1
fi

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORTS_FILE="$SCRIPT_DIR/../ports.json"
TEMPLATE_FILE="$SCRIPT_DIR/../nginx-templates/location-block.template"

# Validate inputs
if [ ! -f "$PORTS_FILE" ]; then
  echo "❌ ports.json not found at: $PORTS_FILE" >&2
  exit 1
fi

if [ ! -f "$TEMPLATE_FILE" ]; then
  echo "❌ Template not found at: $TEMPLATE_FILE" >&2
  exit 1
fi

# Get port assignment
PORT=$(jq -r ".\"$SITE_NAME\" // empty" "$PORTS_FILE")

if [ -z "$PORT" ] || [ "$PORT" = "null" ]; then
  echo "❌ No port assigned for: $SITE_NAME" >&2
  echo "   Run: ./scripts/assign-port.sh $SITE_NAME" >&2
  exit 1
fi

# Generate config from template
NGINX_CONFIG=$(cat "$TEMPLATE_FILE" | sed "s/{{SITE_NAME}}/$SITE_NAME/g" | sed "s/{{PORT}}/$PORT/g")

# Output
if [ -z "$OUTPUT_FILE" ]; then
  # Print to stdout
  echo "$NGINX_CONFIG"
else
  # Save to file
  echo "$NGINX_CONFIG" > "$OUTPUT_FILE"
  echo "✅ nginx config written to: $OUTPUT_FILE" >&2
  echo "" >&2
  echo "To add to main config:" >&2
  echo "  sudo nano $WS_NGINX_CONFIG" >&2
  echo "" >&2
  echo "Or to test:" >&2
  echo "  cat $OUTPUT_FILE" >&2
fi

exit 0
