#!/bin/bash
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi
# Main Script Execution
read -p "What is the FQDN of your MultiPortal Installation?: " HOST_NAME

WEB_DIR="/var/www/$HOST_NAME"

if [ -d "$WEB_DIR" ]; then
    echo "MultiPortal Installation exists. Proceeding..."
    # Add your commands here to proceed
else
    echo "MultiPortal Installation does not exist. Did you type your hostname "${HOST_NAME}" correctly?"
    echo "Exiting..."
    exit 1
fi

CADDYSERVER_CONF="/etc/caddy/Caddyfile"
# Function to configure CaddyServer
configure_caddy() {
    echo "Configuring CaddyServer..."
    cat > "$CADDYSERVER_CONF" << EOF
${HOST_NAME} {
    @css path *.css
    header @css Content-Type text/css
    root * /var/www/${HOST_NAME}/backend/web
    encode gzip
    file_server

    php_fastcgi unix//var/run/php/php${PHPVERSION}-fpm.sock {
        index index.php
    }

    # Add headers
    header {
        Access-Control-Allow-Origin *
        Access-Control-Allow-Methods "GET, POST, OPTIONS"
        x-frame-options SAMEORIGIN
        Access-Control-Allow-Headers "Content-Type, Authorization"
    }

    # Error and access logs
    log {
        output file /var/log/caddy/${HOST_NAME}.log
        level error
    }
    
    # PHP handling
    route / {
        try_files {path} {path}/ /index.php?{query}
        php_fastcgi unix//var/run/php/php8.2-fpm.sock {
            env PHP_FCGI_MAX_REQUESTS 1000
        }
    }

    # Static files
    route / {
        file_server
    }

    # Reverse proxy to Node.js server
    reverse_proxy /wss* localhost:8081 {
        header_up Host {host}
        header_up X-Real-IP {remote}
    }
}
EOF
}

configure_caddy
