#!/usr/bin/env bash
#
# onx-webserver-vhost-panel-generate — Panel için driver-spesifik vhost dosyası üret.
#
# Input: {"driver":"apache|nginx|openlitespeed|caddy","hostname":"...","ssl_dir":"...","panel_port":666,"php_sock":"..."}
# Output: {"ok":true,"driver":"X","vhost_path":"/etc/.../onoxsoft-panel.X.conf","backup_existing":"..."}
#
# Strategy:
#   - Driver template'i ile vhost dosyası yarat (overwrite yapmadan önce backup)
#   - Apache: /etc/httpd/conf.d/onoxsoft-panel.conf (mevcut, dokunma)
#   - Nginx: /etc/nginx/conf.d/onoxsoft-panel.conf
#   - OLS: /usr/local/lsws/conf/vhosts/onoxsoft-panel/vhconf.conf
#   - Caddy: /etc/caddy/conf.d/onoxsoft-panel.caddyfile

set -uo pipefail

input="$(cat 2>/dev/null || echo '{}')"
driver="$(echo "$input" | jq -r '.driver // empty')"
hostname="$(echo "$input" | jq -r '.hostname // empty')"
ssl_dir="$(echo "$input" | jq -r '.ssl_dir // "/etc/onoxsoft/ssl"')"
panel_port="$(echo "$input" | jq -r '.panel_port // 666')"
php_sock="$(echo "$input" | jq -r '.php_sock // "/run/php-fpm/onoxsoft.sock"')"
docroot="$(echo "$input" | jq -r '.docroot // "/opt/onoxsoft/public"')"

[[ -z "$driver" || -z "$hostname" ]] && {
    jq -nc '{ok:false,error:"driver+hostname required"}' >&2
    exit 1
}

generate_apache() {
    cat <<APACHE_EOF
# Onoxsoft Panel — Apache vhost (auto-generated by vhost-panel-generate)
Listen ${panel_port} https
<VirtualHost *:${panel_port}>
    ServerName ${hostname}
    DocumentRoot ${docroot}

    SSLEngine on
    SSLCertificateFile    ${ssl_dir}/${hostname}.fullchain
    SSLCertificateKeyFile ${ssl_dir}/${hostname}.key

    <IfModule mod_security2.c>
        SecRuleEngine Off
    </IfModule>

    <Directory ${docroot}>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php\$>
        SetHandler "proxy:unix:${php_sock}|fcgi://localhost"
        SetEnv HTTPS on
        SetEnv HTTP_X_FORWARDED_PROTO https
        SetEnv HTTP_X_FORWARDED_PORT ${panel_port}
    </FilesMatch>

    # phpMyAdmin .php -> dedicated FPM pool (panel pool pma'yi 503'luyor; switch-proof)
    # Alias /phpmyadmin RPM'in /etc/httpd/conf.d/phpMyAdmin.conf'undan gelir.
    <Directory /usr/share/phpMyAdmin>
        <FilesMatch \.php\$>
            SetHandler "proxy:unix:/var/opt/remi/php82/run/php-fpm/onoxsoft-phpmyadmin.sock|fcgi://localhost"
            SetEnv HTTPS on
        </FilesMatch>
    </Directory>

    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"

    # Admin Terminal (ttyd WS reverse-proxy) — /admin/terminal/ws -> 127.0.0.1:7681 (switch-proof)
    # ttyd -c basic-auth ister; tarayıcı WS'e header ekleyemez → Apache Authorization
    # header'ını enjekte eder (include dosyası, secret'tan üretilir). Asıl kapı: ttyd AuthToken.
    <IfModule mod_proxy_wstunnel.c>
        IncludeOptional /etc/onoxsoft/terminal-proxy-auth.conf
        ProxyPass        /admin/terminal/ws  ws://127.0.0.1:7681/ws  retry=0
        ProxyPassReverse /admin/terminal/ws  ws://127.0.0.1:7681/ws
    </IfModule>

    ErrorLog  /var/log/httpd/onoxsoft-panel-ssl-error.log
    CustomLog /var/log/httpd/onoxsoft-panel-ssl-access.log combined
</VirtualHost>
APACHE_EOF
}

generate_nginx() {
    cat <<NGINX_EOF
# Onoxsoft Panel — Nginx vhost (auto-generated by vhost-panel-generate)
server {
    listen ${panel_port} ssl http2;
    listen [::]:${panel_port} ssl http2;
    server_name ${hostname};
    root ${docroot};
    index index.php;

    ssl_certificate     ${ssl_dir}/${hostname}.fullchain;
    ssl_certificate_key ${ssl_dir}/${hostname}.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    access_log /var/log/nginx/onoxsoft-panel-access.log;
    error_log  /var/log/nginx/onoxsoft-panel-error.log;

    # Security headers
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;

    # Laravel front controller
    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    # Hidden + sensitive files
    location ~ /\\.(?!well-known).* { deny all; }

    # PHP-FPM
    location ~ \\.php\$ {
        fastcgi_split_path_info ^(.+\\.php)(/.+)\$;
        fastcgi_pass unix:${php_sock};
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param PATH_INFO       \$fastcgi_path_info;
        fastcgi_param HTTPS           on;
        fastcgi_param HTTP_X_FORWARDED_PROTO https;
        fastcgi_param HTTP_X_FORWARDED_PORT ${panel_port};

        # v71.2b: Buffer artırıldı — Laravel session + CSRF + Inertia state header'ları
        # default 16KB'i aşıyor → "upstream sent too big header" → 502.
        fastcgi_buffer_size        128k;
        fastcgi_buffers            8 256k;
        fastcgi_busy_buffers_size  256k;
        fastcgi_temp_file_write_size 256k;
        fastcgi_read_timeout       180;
        fastcgi_connect_timeout    30;
    }
}
NGINX_EOF
}

generate_openlitespeed() {
    # v80.9 KRİTİK FIX: v79.9 working pattern — LSAPI native lsphp82 binary
    # + apache:webserver + own socket (lsphp82-panel.sock). Önceki format
    # (FPM socket + path eksik + extUser yok) sodium ext.'i ile MIME type 403
    # veriyordu. Bu format production'da v78+v79 verify edilmiş, panel 200 döner.
    cat <<OLS_EOF
# Onoxsoft Panel — OpenLiteSpeed vhost (v80.9 LSAPI native, working pattern)
docRoot                   ${docroot}
vhDomain                  ${hostname}
enableGzip                1

errorlog \$VH_ROOT/logs/error.log {
  useServer               1
  logLevel                ERROR
}

accesslog \$VH_ROOT/logs/access.log {
  useServer               0
}

index {
  useServer               0
  indexFiles              index.php
}

scripthandler {
  add                     lsapi:lsphp82panel php
}

extprocessor lsphp82panel {
  type                    lsapi
  address                 uds://tmp/lshttpd/lsphp82-panel.sock
  maxConns                10
  env                     LSAPI_CHILDREN=10
  initTimeout             60
  retryTimeout            0
  persistConn             1
  pcKeepAliveTimeout      60
  respBuffer              0
  autoStart               1
  path                    /usr/local/lsws/lsphp82/bin/lsphp
  extUser                 apache
  extGroup                webserver
  memSoftLimit            512M
  memHardLimit            1024M
}

context / {
  location                ${docroot}
  allowBrowse             1
  indexFiles              index.php
  rewrite {
    enable                1
    rules                 <<<END_RULES
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\$ /index.php [L]
END_RULES
  }
}

# phpMyAdmin context'leri — ayri lsphp82pma extprocessor (panel pool ile cakismaz; switch-proof)
context /phpmyadmin {
  location                /usr/share/phpMyAdmin
  allowBrowse             1
  indexFiles              index.php
  scripthandler {
    add                   lsapi:lsphp82pma php
  }
  rewrite {
    enable                0
  }
}

context /phpMyAdmin {
  location                /usr/share/phpMyAdmin
  allowBrowse             1
  indexFiles              index.php
  scripthandler {
    add                   lsapi:lsphp82pma php
  }
}

extprocessor lsphp82pma {
  type                    lsapi
  address                 uds://tmp/lshttpd/lsphp82-pma.sock
  maxConns                5
  env                     LSAPI_CHILDREN=5
  initTimeout             60
  retryTimeout            0
  persistConn             1
  pcKeepAliveTimeout      60
  respBuffer              0
  autoStart               1
  path                    /usr/local/lsws/lsphp82/bin/lsphp
  extUser                 apache
  extGroup                webserver
  memSoftLimit            256M
  memHardLimit            512M
}

vhssl {
  keyFile                 ${ssl_dir}/${hostname}.key
  certFile                ${ssl_dir}/${hostname}.fullchain
  certChain               1
  sslProtocol             24
  enableECDHE             1
  renegProtection         1
  sslSessionCache         1
}
OLS_EOF
}

generate_caddy() {
    cat <<CADDY_EOF
# Onoxsoft Panel — Caddy site block (auto-generated)
${hostname}:${panel_port} {
    root * ${docroot}
    encode gzip

    tls ${ssl_dir}/${hostname}.fullchain ${ssl_dir}/${hostname}.key

    php_fastcgi unix/${php_sock}
    file_server

    header {
        Strict-Transport-Security "max-age=63072000; includeSubDomains"
        X-Frame-Options "SAMEORIGIN"
        X-Content-Type-Options "nosniff"
    }

    log {
        output file /var/log/caddy/onoxsoft-panel-access.log
        format json
    }
}
CADDY_EOF
}

# Driver-specific output path + write
case "$driver" in
    apache)
        vhost_path="/etc/httpd/conf.d/onoxsoft-panel.conf"
        ;;
    nginx)
        mkdir -p /etc/nginx/conf.d 2>/dev/null
        vhost_path="/etc/nginx/conf.d/onoxsoft-panel.conf"
        # Nginx log dizini
        mkdir -p /var/log/nginx 2>/dev/null
        ;;
    openlitespeed)
        mkdir -p /usr/local/lsws/conf/vhosts/onoxsoft-panel 2>/dev/null
        vhost_path="/usr/local/lsws/conf/vhosts/onoxsoft-panel/vhconf.conf"
        ;;
    caddy)
        mkdir -p /etc/caddy/conf.d 2>/dev/null
        vhost_path="/etc/caddy/conf.d/onoxsoft-panel.caddyfile"
        ;;
    *)
        jq -nc --arg d "$driver" '{ok:false,error:"unsupported driver",driver:$d}' >&2
        exit 1
        ;;
esac

# Backup existing
backup_path=""
if [[ -f "$vhost_path" ]]; then
    backup_path="${vhost_path}.bak.$(date +%Y%m%d-%H%M%S)"
    cp -a "$vhost_path" "$backup_path"
fi

# Generate + write
case "$driver" in
    apache)         generate_apache         > "$vhost_path" ;;
    nginx)          generate_nginx          > "$vhost_path" ;;
    openlitespeed)  generate_openlitespeed  > "$vhost_path" ;;
    caddy)          generate_caddy          > "$vhost_path" ;;
esac

chmod 644 "$vhost_path"

jq -nc \
    --arg driver "$driver" --arg path "$vhost_path" --arg backup "$backup_path" \
    --arg hostname "$hostname" --argjson port "$panel_port" \
    '{ok:true, driver:$driver, vhost_path:$path, backup_existing:$backup, hostname:$hostname, port:$port,
      message:"Panel vhost dosyası üretildi. Switch akışı bu dosyayı yükler."}'
