#!/bin/bash

# PHI|OS Uniphil.ch Nginx Configuration Automation
# Automatically applies the correct nginx configuration for uniphil.ch

set -e

# Load environment variables if .env file exists
if [ -f ".env" ]; then
    source .env
fi

# Configuration variables with defaults
DOMAIN="${DOMAIN:-uniphil.ch}"
WEBAPP_PORT="${WEBAPP_PORT:-3300}"
API_PORT="${API_PORT:-3001}"
NGINX_AVAILABLE="/etc/nginx/sites-available/${DOMAIN}.conf"
NGINX_ENABLED="/etc/nginx/sites-enabled/${DOMAIN}.conf"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}[PHI|OS] Applying nginx configuration for ${DOMAIN}...${NC}"

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}[ERROR] This script must be run as root${NC}"
    exit 1
fi

# Backup existing configuration if it exists
if [ -f "${NGINX_AVAILABLE}" ]; then
    echo -e "${YELLOW}[NGINX] Backing up existing configuration...${NC}"
    cp "${NGINX_AVAILABLE}" "${NGINX_AVAILABLE}.backup-$(date +%Y%m%d-%H%M%S)"
    echo -e "${GREEN}[NGINX] Backup created${NC}"
fi

# Generate the nginx configuration
echo -e "${YELLOW}[NGINX] Generating configuration...${NC}"

cat > "${NGINX_AVAILABLE}" << EONGINX
server {
    listen 80;
    server_name ${DOMAIN} www.${DOMAIN};
    return 301 https://\[host\]\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name ${DOMAIN} www.${DOMAIN};
    
    ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/${DOMAIN}/chain.pem;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline' 'unsafe-eval'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
    # Proxy all requests to the PHI|OS container
    location / {
        proxy_pass http://localhost:${WEBAPP_PORT};
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    # API proxy to PHI|OS services
    location /api/ {
        proxy_pass http://localhost:${API_PORT}/api/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    # Websocket support for realtime features
    location /ws/ {
        proxy_pass http://localhost:${API_PORT}/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
    }
}
EONGINX

echo -e "${GREEN}[NGINX] Configuration generated${NC}"

# Enable the site
if [ -f "${NGINX_ENABLED}" ]; then
    rm "${NGINX_ENABLED}"
fi
ln -s "${NGINX_AVAILABLE}" "${NGINX_ENABLED}"
echo -e "${GREEN}[NGINX] Site enabled${NC}"

# Test nginx configuration
echo -e "${YELLOW}[NGINX] Testing configuration...${NC}"
if nginx -t; then
    echo -e "${GREEN}[NGINX] Configuration test passed${NC}"
else
    echo -e "${RED}[ERROR] Nginx configuration test failed${NC}"
    exit 1
fi

# Reload nginx
echo -e "${YELLOW}[NGINX] Reloading nginx...${NC}"
systemctl reload nginx
echo -e "${GREEN}[NGINX] Nginx reloaded${NC}"

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║        PHI|OS Nginx Configuration Applied Successfully      ║"
echo -e "║                                                           ║"
echo -e "║  Domain: https://${DOMAIN}                                ║"
echo -e "║  Webapp Port: ${WEBAPP_PORT}                               ║"
echo -e "║  API Port: ${API_PORT}                                     ║"
echo -e "║  Nginx Config: ${NGINX_AVAILABLE}                        ║"
echo -e "║                                                           ║"
echo -e "║  Services should be running on:                          ║"
echo -e "║  - Web: https://${DOMAIN}                                 ║"
echo -e "║  - API: https://${DOMAIN}/api/                            ║"
echo -e "║  - WS: wss://${DOMAIN}/ws/                                ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0