#!/bin/bash

# Apache Configuration Script for Vision Videoke Subdirectory Setup
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> [subdirectory]"
    echo "Example: $0 example.com music"
    exit 1
fi

DOMAIN=$1
SUBDIRECTORY=${2:-music}
APACHE_CONF_DIR="/etc/httpd/conf.d"
DOCUMENT_ROOT="/var/www/html"
APP_DIR="$DOCUMENT_ROOT/$SUBDIRECTORY"
VHOST_CONF="$APACHE_CONF_DIR/visionvideoke-$SUBDIRECTORY.conf"

log "Configuring Apache for Vision Videoke at /$SUBDIRECTORY"

# Check if Apache is installed
if ! command -v httpd &> /dev/null && ! command -v apache2 &> /dev/null; then
    error "Apache is not installed. Please install Apache first."
fi

# Detect Apache service name (httpd for RHEL/CentOS, apache2 for Debian/Ubuntu)
if systemctl list-units --type=service | grep -q "httpd.service"; then
    APACHE_SERVICE="httpd"
    APACHE_CONF_DIR="/etc/httpd/conf.d"
    APACHE_MODULES_DIR="/etc/httpd/conf.modules.d"
elif systemctl list-units --type=service | grep -q "apache2.service"; then
    APACHE_SERVICE="apache2"
    APACHE_CONF_DIR="/etc/apache2/sites-available"
    APACHE_MODULES_DIR="/etc/apache2/mods-available"
else
    error "Could not detect Apache service. Please ensure Apache is installed and running."
fi

log "Detected Apache service: $APACHE_SERVICE"

# Check if Apache is running
if ! systemctl is-active --quiet $APACHE_SERVICE; then
    warn "Apache is not running. Starting Apache..."
    sudo systemctl start $APACHE_SERVICE
fi

# Enable required Apache modules
log "Enabling required Apache modules..."

enable_module() {
    local module=$1
    local module_file=$2
    
    if [ "$APACHE_SERVICE" = "httpd" ]; then
        # RHEL/CentOS/Amazon Linux
        if ! httpd -M 2>/dev/null | grep -q "${module}_module"; then
            info "Enabling module: $module"
            if [ -f "/etc/httpd/conf.modules.d/$module_file" ]; then
                sudo sed -i "s/^#LoadModule $module/LoadModule $module/" "/etc/httpd/conf.modules.d/$module_file"
            else
                echo "LoadModule ${module}_module modules/mod_${module}.so" | sudo tee -a /etc/httpd/conf/httpd.conf
            fi
        fi
    else
        # Debian/Ubuntu
        sudo a2enmod $module 2>/dev/null || warn "Module $module may already be enabled or not available"
    fi
}

# Enable required modules
enable_module "rewrite" "00-base.conf"
enable_module "headers" "00-base.conf"
enable_module "expires" "00-optional.conf"
enable_module "deflate" "00-base.conf"
enable_module "proxy" "00-proxy.conf"
enable_module "proxy_http" "00-proxy.conf"
enable_module "proxy_wstunnel" "00-proxy.conf"

# Create application directory
log "Creating application directory: $APP_DIR"
sudo mkdir -p $APP_DIR
sudo chown apache:apache $APP_DIR 2>/dev/null || sudo chown www-data:www-data $APP_DIR 2>/dev/null || sudo chown ec2-user:ec2-user $APP_DIR

# Create Apache configuration for the subdirectory
log "Creating Apache configuration..."
sudo tee $VHOST_CONF > /dev/null <<EOF
# Vision Videoke Apache Configuration
# Subdirectory setup at /$SUBDIRECTORY
# Generated on $(date)

# Main subdirectory configuration
<Directory "$APP_DIR">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    
    # Enable rewrite engine for React Router
    RewriteEngine On
    
    # Handle React Router (SPA) routing
    # Redirect all requests to index.html except for actual files
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/api/
    RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/health\$
    RewriteRule ^(.*)$ /$SUBDIRECTORY/index.html [L,QSA]
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # HTTPS security header (only if using HTTPS)
    <If "%{HTTPS} == 'on'">
        Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    </If>
    
    # CORS headers for API requests
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
    
    # Handle preflight OPTIONS requests
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ \$1 [R=200,L]
</Directory>

# Proxy configuration for Node.js backend API
# This forwards API requests to the Node.js application running on port 3001
<Location "/$SUBDIRECTORY/api">
    ProxyPreserveHost On
    ProxyPass http://127.0.0.1:3001/api
    ProxyPassReverse http://127.0.0.1:3001/api
    
    # WebSocket support (if needed)
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/$SUBDIRECTORY/api/(.*) "ws://127.0.0.1:3001/api/\$1" [P,L]
</Location>

# File upload handling with increased limits
<Location "/$SUBDIRECTORY/api/upload">
    # Increase upload limits
    LimitRequestBody 104857600  # 100MB
    
    # Extended timeouts for file uploads
    ProxyTimeout 300
    ProxyPass http://127.0.0.1:3001/api/upload
    ProxyPassReverse http://127.0.0.1:3001/api/upload
</Location>

# Health check endpoint
<Location "/$SUBDIRECTORY/health">
    ProxyPass http://127.0.0.1:3001/health
    ProxyPassReverse http://127.0.0.1:3001/health
</Location>

# Static file caching for performance
<LocationMatch "/$SUBDIRECTORY/.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$">
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
    Header append Cache-Control "public, immutable"
</LocationMatch>

# HTML files with short cache
<LocationMatch "/$SUBDIRECTORY/.*\.html\$">
    ExpiresActive On
    ExpiresDefault "access plus 1 hour"
    Header append Cache-Control "public, must-revalidate"
</LocationMatch>

# Gzip compression for better performance
<Location "/$SUBDIRECTORY">
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png)\$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI \
        \.(?:exe|t?gz|zip|bz2|sit|rar)\$ no-gzip dont-vary
</Location>

# Security: Block access to sensitive files
<LocationMatch "/$SUBDIRECTORY/(\.env|package\.json|ecosystem\.config\.js|\.git)">
    Require all denied
</LocationMatch>

# Rate limiting (if mod_evasive is available)
<IfModule mod_evasive24.c>
    <Location "/$SUBDIRECTORY/api">
        DOSHashTableSize    2048
        DOSPageCount        10
        DOSPageInterval     1
        DOSSiteCount        50
        DOSSiteInterval     1
        DOSBlockingPeriod   600
    </Location>
</IfModule>
EOF

# Create .htaccess file for the subdirectory
log "Creating .htaccess file..."
sudo tee $APP_DIR/.htaccess > /dev/null <<EOF
# Vision Videoke .htaccess Configuration
# Generated on $(date)

RewriteEngine On

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # CORS headers for API requests
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
</IfModule>

# Handle preflight OPTIONS requests
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ \$1 [R=200,L]

# React Router (SPA) routing
# Redirect all non-file requests to index.html for client-side routing
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/api/
RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/health\$
RewriteRule ^(.*)$ index.html [L,QSA]

# Static file caching
<IfModule mod_expires.c>
    ExpiresActive On
    
    # Cache static assets for 1 year
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/ico "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/eot "access plus 1 year"
    
    # Cache HTML files for 1 hour
    ExpiresByType text/html "access plus 1 hour"
</IfModule>

# Gzip compression
<IfModule mod_deflate.c>
    SetOutputFilter DEFLATE
    
    # Don't compress images
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png)\$ no-gzip dont-vary
    
    # Don't compress archives
    SetEnvIfNoCase Request_URI \
        \.(?:exe|t?gz|zip|bz2|sit|rar)\$ no-gzip dont-vary
</IfModule>

# Security: Block access to sensitive files
<FilesMatch "(\.env|package\.json|ecosystem\.config\.js|\.git.*|\.htaccess)">
    Require all denied
</FilesMatch>

# Directory browsing disabled for security
Options -Indexes

# Follow symbolic links
Options +FollowSymLinks
EOF

# Set proper permissions
sudo chown apache:apache $APP_DIR/.htaccess 2>/dev/null || sudo chown www-data:www-data $APP_DIR/.htaccess 2>/dev/null || sudo chown ec2-user:ec2-user $APP_DIR/.htaccess
sudo chmod 644 $APP_DIR/.htaccess

# Enable the site (for Debian/Ubuntu)
if [ "$APACHE_SERVICE" = "apache2" ]; then
    sudo a2ensite visionvideoke-$SUBDIRECTORY 2>/dev/null || true
fi

# Test Apache configuration
log "Testing Apache configuration..."
if sudo $APACHE_SERVICE -t; then
    log "Apache configuration test passed"
else
    error "Apache configuration test failed"
fi

# Reload Apache configuration
log "Reloading Apache configuration..."
sudo systemctl reload $APACHE_SERVICE

# Create a simple index.html for testing
log "Creating test index.html..."
sudo tee $APP_DIR/index.html > /dev/null <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vision Videoke - Setup Complete</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            padding: 50px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .container {
            max-width: 600px;
            padding: 40px;
            background: rgba(255,255,255,0.1);
            border-radius: 20px;
            backdrop-filter: blur(10px);
        }
        h1 { font-size: 3em; margin-bottom: 20px; }
        p { font-size: 1.2em; line-height: 1.6; }
        .status { 
            background: rgba(0,255,0,0.2); 
            padding: 10px 20px; 
            border-radius: 10px; 
            margin: 20px 0;
            border: 1px solid rgba(0,255,0,0.3);
        }
        .info {
            background: rgba(255,255,255,0.1);
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎬 Vision Videoke</h1>
        <div class="status">✅ Apache Configuration Complete!</div>
        <p>Your Vision Videoke platform is ready for deployment in the <strong>/$SUBDIRECTORY</strong> subdirectory.</p>
        
        <div class="info">
            <h3>Configuration Details:</h3>
            <ul>
                <li><strong>Domain:</strong> $DOMAIN</li>
                <li><strong>Subdirectory:</strong> /$SUBDIRECTORY</li>
                <li><strong>Document Root:</strong> $APP_DIR</li>
                <li><strong>API Endpoint:</strong> /$SUBDIRECTORY/api</li>
                <li><strong>Health Check:</strong> /$SUBDIRECTORY/health</li>
            </ul>
        </div>
        
        <p><strong>Next Steps:</strong></p>
        <ul style="text-align: left; display: inline-block;">
            <li>Deploy your Vision Videoke application files</li>
            <li>Configure environment variables</li>
            <li>Start the Node.js backend service</li>
            <li>Test the complete setup</li>
        </ul>
        
        <p style="margin-top: 30px; font-size: 0.9em; opacity: 0.8;">
            Server: $DOMAIN | Path: /$SUBDIRECTORY | Status: Ready
        </p>
    </div>
</body>
</html>
EOF

sudo chown apache:apache $APP_DIR/index.html 2>/dev/null || sudo chown www-data:www-data $APP_DIR/index.html 2>/dev/null || sudo chown ec2-user:ec2-user $APP_DIR/index.html

# Create management scripts
log "Creating management scripts..."

# Create restart script
cat > /home/ec2-user/restart-apache.sh <<EOF
#!/bin/bash
echo "Restarting Apache..."
sudo systemctl restart $APACHE_SERVICE
echo "Apache restarted successfully"
EOF
chmod +x /home/ec2-user/restart-apache.sh

# Create status check script
cat > /home/ec2-user/check-apache-status.sh <<EOF
#!/bin/bash
echo "=== Apache Status ==="
sudo systemctl status $APACHE_SERVICE --no-pager -l
echo ""
echo "=== Apache Configuration Test ==="
sudo $APACHE_SERVICE -t
echo ""
echo "=== Vision Videoke Directory ==="
ls -la $APP_DIR
echo ""
echo "=== Active Apache Modules ==="
if [ "$APACHE_SERVICE" = "httpd" ]; then
    httpd -M | grep -E "(rewrite|headers|expires|deflate|proxy)"
else
    apache2ctl -M | grep -E "(rewrite|headers|expires|deflate|proxy)"
fi
EOF
chmod +x /home/ec2-user/check-apache-status.sh

log "Apache configuration completed successfully!"
log ""
log "Configuration Summary:"
log "- Domain: $DOMAIN"
log "- Subdirectory: /$SUBDIRECTORY"
log "- Document Root: $APP_DIR"
log "- Apache Config: $VHOST_CONF"
log "- .htaccess: $APP_DIR/.htaccess"
log ""
log "Access your application at:"
log "- http://$DOMAIN/$SUBDIRECTORY"
log "- https://$DOMAIN/$SUBDIRECTORY (if SSL is configured)"
log ""
log "Management commands:"
log "- ./restart-apache.sh        - Restart Apache"
log "- ./check-apache-status.sh   - Check Apache status"
log "- sudo systemctl reload $APACHE_SERVICE - Reload Apache config"
log ""
log "Next steps:"
log "1. Deploy your Vision Videoke application to $APP_DIR"
log "2. Configure environment variables"
log "3. Start the Node.js backend on port 3001"
log "4. Test the application at http://$DOMAIN/$SUBDIRECTORY"

