#!/bin/bash
# Install nginx config for core_room
# Run with: sudo ./install-nginx.sh

set -e

# Application user (can be overridden with environment variable)
APP_USER="${APP_USER:-mariano}"
APP_HOME="/home/${APP_USER}"

NGINX_SOURCE="${APP_HOME}/core_room/ctrl/server/nginx/core_room.conf"
NGINX_AVAILABLE="/etc/nginx/sites-available/core_room.conf"
NGINX_ENABLED="/etc/nginx/sites-enabled/core_room.conf"

echo "=== Installing nginx config for core_room ==="
echo "App user: $APP_USER"
echo "App home: $APP_HOME"
echo ""

# Check if source file exists
if [ ! -f "$NGINX_SOURCE" ]; then
    echo "Error: Source file not found: $NGINX_SOURCE"
    exit 1
fi

# Copy to sites-available
echo "Installing config to sites-available..."
cp "$NGINX_SOURCE" "$NGINX_AVAILABLE"
echo "  ✓ Config installed to $NGINX_AVAILABLE"

# Create symlink to sites-enabled
echo "Enabling config..."
ln -sf "$NGINX_AVAILABLE" "$NGINX_ENABLED"
echo "  ✓ Config enabled"

# Test nginx configuration
echo ""
echo "Testing nginx configuration..."
if nginx -t; then
    echo "  ✓ Nginx config is valid"

    # Reload nginx
    echo ""
    echo "Reloading nginx..."
    systemctl reload nginx
    echo "  ✓ Nginx reloaded"

    echo ""
    echo "=== Installation complete ==="
else
    echo ""
    echo "Error: Nginx configuration test failed"
    echo "Config was installed but nginx was not reloaded"
    exit 1
fi
