#!/bin/bash

# Nginx Configuration Script for Vision Videoke
set -e

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

info() {
    echo -e "${BLUE}[INFO] $1${NC}"
}

# Check if domain is provided
if [ -z "$1" ]; then
    error "Usage: $0 <domain-name>"
    echo "Example: $0 visionvideoke.com"
    exit 1
fi

DOMAIN=$1
NGINX_CONF="/etc/nginx/sites-available/visionvideoke"
NGINX_ENABLED="/etc/nginx/sites-enabled/visionvideoke"

log "Configuring Nginx for domain: $DOMAIN"

# Check if nginx is installed
if ! command -v nginx &> /dev/null; then
    error "Nginx is not installed. Please run ec2-setup.sh first."
fi

# Create nginx configuration
log "Creating nginx configuration..."
sudo tee $NGINX_CONF > /dev/null <<EOF
# Vision Videoke Nginx Configuration
# Generated on $(date)

# Rate limiting
limit_req_zone \$binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone \$binary_remote_addr zone=upload:10m rate=2r/s;

# Upstream for Node.js application
upstream visionvideoke_app {
    server 127.0.0.1:3000;
    keepalive 32;
}

# HTTP server (will redirect to HTTPS after SSL setup)
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    
    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # Temporary location for initial setup (before SSL)
    location / {
        proxy_pass http://visionvideoke_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass \$http_upgrade;
    }
    
    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\\n";
        add_header Content-Type text/plain;
    }
}
EOF

# Enable the site
log "Enabling nginx site..."
sudo ln -sf $NGINX_CONF $NGINX_ENABLED

# Remove default nginx site if it exists
if [ -f "/etc/nginx/sites-enabled/default" ]; then
    log "Removing default nginx site..."
    sudo rm -f /etc/nginx/sites-enabled/default
fi

# Test nginx configuration
log "Testing nginx configuration..."
sudo nginx -t

# Start and enable nginx
log "Starting nginx..."
sudo systemctl start nginx
sudo systemctl enable nginx

# Create SSL configuration update script
log "Creating SSL configuration update script..."
cat > /home/ec2-user/update-nginx-ssl.sh <<EOF
#!/bin/bash

# Update nginx configuration to use SSL
DOMAIN="$DOMAIN"
NGINX_CONF="/etc/nginx/sites-available/visionvideoke"

# Backup current configuration
sudo cp \$NGINX_CONF \$NGINX_CONF.backup

# Create SSL-enabled configuration
sudo tee \$NGINX_CONF > /dev/null <<'SSLEOF'
# Vision Videoke Nginx Configuration with SSL
# Updated on \$(date)

# Rate limiting
limit_req_zone \$binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone \$binary_remote_addr zone=upload:10m rate=2r/s;

# Upstream for Node.js application
upstream visionvideoke_app {
    server 127.0.0.1:3000;
    keepalive 32;
}

# HTTP to HTTPS redirect
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    
    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # Redirect all other traffic to HTTPS
    location / {
        return 301 https://\$server_name\$request_uri;
    }
}

# HTTPS server
server {
    listen 443 ssl http2;
    server_name $DOMAIN www.$DOMAIN;
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
    
    # SSL Security Settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;
    
    # Security Headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # Logging
    access_log /var/log/nginx/visionvideoke_access.log;
    error_log /var/log/nginx/visionvideoke_error.log;
    
    # Root directory for static files
    root /var/www/visionvideoke/dist;
    index index.html;
    
    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;
    
    # Client upload limits
    client_max_body_size 100M;
    client_body_timeout 60s;
    client_header_timeout 60s;
    
    # API routes with rate limiting
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        
        proxy_pass http://visionvideoke_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass \$http_upgrade;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # Upload endpoints with stricter rate limiting
    location /api/upload {
        limit_req zone=upload burst=5 nodelay;
        
        proxy_pass http://visionvideoke_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass \$http_upgrade;
        
        # Extended timeouts for uploads
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;
    }
    
    # Static files with caching
    location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header X-Content-Type-Options nosniff;
        
        try_files \$uri \$uri/ @proxy;
    }
    
    # HTML files with short cache
    location ~* \\.html\$ {
        expires 1h;
        add_header Cache-Control "public, must-revalidate";
        add_header X-Content-Type-Options nosniff;
        
        try_files \$uri \$uri/ @proxy;
    }
    
    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\\n";
        add_header Content-Type text/plain;
    }
    
    # Default location - serve React app
    location / {
        try_files \$uri \$uri/ @proxy;
    }
    
    # Proxy fallback for SPA routing
    location @proxy {
        proxy_pass http://visionvideoke_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass \$http_upgrade;
    }
    
    # Block access to sensitive files
    location ~ /\\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
SSLEOF

# Test and reload nginx
sudo nginx -t && sudo systemctl reload nginx

echo "Nginx configuration updated for SSL"
EOF

chmod +x /home/ec2-user/update-nginx-ssl.sh

# Create log rotation for nginx
log "Setting up nginx log rotation..."
sudo tee /etc/logrotate.d/nginx-visionvideoke > /dev/null <<EOF
/var/log/nginx/visionvideoke_*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 nginx nginx
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 \`cat /var/run/nginx.pid\`
        fi
    endscript
}
EOF

log "Nginx configuration completed successfully!"
log ""
log "Next steps:"
log "1. Point your domain $DOMAIN to this server's IP address"
log "2. Wait for DNS propagation (may take up to 24 hours)"
log "3. Run SSL setup: ./setup-ssl.sh $DOMAIN"
log "4. Deploy your application: ./deploy-app.sh"
log ""
log "To check nginx status: sudo systemctl status nginx"
log "To view nginx logs: sudo tail -f /var/log/nginx/visionvideoke_*.log"
log "To test configuration: sudo nginx -t"

