#!/bin/bash

#############################################
# All-in-One Script Server Setup für Debian 12
# Mit Web-Interface und Upload-Funktion
#############################################

set -e

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

# Logging
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }

# Variablen
SCRIPT_DIR="/var/www/scripts"
SERVER_IP=$(hostname -I | awk '{print $1}')
ADMIN_PASSWORD=""
PORT="80"

# Banner
clear
cat << "EOF"
╔═══════════════════════════════════════╗
║     SCRIPT SERVER SETUP v2.0          ║
║     Web-Interface + Upload            ║
╚═══════════════════════════════════════╝
EOF

# Root Check
if [[ $EUID -ne 0 ]]; then
    log_error "Bitte als root ausführen: sudo bash $0"
    exit 1
fi

# Parameter
while [[ $# -gt 0 ]]; do
    case $1 in
        -p|--password)
            ADMIN_PASSWORD="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [-p PASSWORD] [--port PORT]"
            echo "  -p, --password    Admin-Passwort für Web-Interface"
            echo "  --port           Port (default: 80)"
            exit 0
            ;;
        *)
            shift
            ;;
    esac
done

# Auto-generiere Passwort falls nicht angegeben
if [ -z "$ADMIN_PASSWORD" ]; then
    ADMIN_PASSWORD=$(openssl rand -base64 12 | tr -d "=+/" | cut -c1-10)
fi

# Installation starten
log_step "Starte Installation..."
log_info "Server IP: $SERVER_IP"
log_info "Port: $PORT"

# System Update
log_step "System Update..."
apt-get update -qq

# Pakete installieren
log_step "Installiere benötigte Pakete..."
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    nginx \
    php-fpm \
    php-cli \
    curl \
    openssl \
    --no-install-recommends

# PHP Version ermitteln
PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;")
log_info "PHP Version: $PHP_VERSION"

# Script-Verzeichnis erstellen
log_step "Erstelle Verzeichnisstruktur..."
mkdir -p $SCRIPT_DIR
chown -R www-data:www-data $SCRIPT_DIR
chmod 755 $SCRIPT_DIR

# Nginx Konfiguration
log_step "Konfiguriere Nginx..."
cat > /etc/nginx/sites-available/script-server << NGINX_CONFIG
server {
    listen $PORT;
    listen [::]:$PORT;
    server_name _;
    
    root $SCRIPT_DIR;
    index index.php index.html;
    
    # Logging
    access_log /var/log/nginx/script-server.access.log;
    error_log /var/log/nginx/script-server.error.log;
    
    # PHP Support
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php${PHP_VERSION}-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }
    
    # Script-Dateien als Plain Text - WICHTIG für SSL/Proxy
    location ~ \.(sh|bash|zsh|py|ps1|pl|rb)$ {
        # Force text/plain - immer, auch bei Proxy
        add_header Content-Type "text/plain; charset=utf-8" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Cache-Control "no-cache, must-revalidate" always;
        
        # Verhindere Download-Dialog
        add_header Content-Disposition "inline" always;
        
        # Für Proxies
        add_header X-Robots-Tag "noindex, nofollow" always;
        
        # Deaktiviere gzip für Scripts (verhindert Encoding-Probleme)
        gzip off;
    }
    
    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }
    
    # Upload Größe
    client_max_body_size 100M;
    
    # Sicherheit
    location ~ /\. {
        deny all;
    }
}
NGINX_CONFIG

# Nginx Site aktivieren
ln -sf /etc/nginx/sites-available/script-server /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Web-Interface erstellen
log_step "Erstelle Web-Interface..."

# Passwort-Hash generieren
PASS_HASH=$(php -r "echo password_hash('$ADMIN_PASSWORD', PASSWORD_DEFAULT);")

cat > $SCRIPT_DIR/index.php << 'PHP_CODE'
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Konfiguration
define('UPLOAD_DIR', __DIR__ . '/');
define('ADMIN_PASS_HASH', 'PASSWORD_HASH_PLACEHOLDER');
define('MAX_FILE_SIZE', 100 * 1024 * 1024); // 100MB

// Funktionen
function formatSize($bytes) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $i = floor(log($bytes, 1024));
    return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
}

function isScript($filename) {
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    return in_array($ext, ['sh', 'bash', 'zsh', 'py', 'pl', 'rb', 'ps1']);
}

// Actions
$message = '';
$messageType = '';

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: /');
    exit;
}

// Login
if (isset($_POST['action']) && $_POST['action'] === 'login') {
    if (password_verify($_POST['password'], ADMIN_PASS_HASH)) {
        $_SESSION['authenticated'] = true;
        $message = 'Login erfolgreich!';
        $messageType = 'success';
    } else {
        $message = 'Falsches Passwort!';
        $messageType = 'error';
    }
}

// Upload (nur wenn eingeloggt)
if (isset($_FILES['upload']) && isset($_SESSION['authenticated'])) {
    $uploadFile = UPLOAD_DIR . basename($_FILES['upload']['name']);
    
    if ($_FILES['upload']['size'] > MAX_FILE_SIZE) {
        $message = 'Datei zu groß! Max: ' . formatSize(MAX_FILE_SIZE);
        $messageType = 'error';
    } elseif ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
        if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadFile)) {
            chmod($uploadFile, 0644);
            $message = 'Upload erfolgreich: ' . basename($_FILES['upload']['name']);
            $messageType = 'success';
        } else {
            $message = 'Upload fehlgeschlagen!';
            $messageType = 'error';
        }
    }
}

// Löschen (nur wenn eingeloggt)
if (isset($_GET['delete']) && isset($_SESSION['authenticated'])) {
    $file = basename($_GET['delete']);
    $filepath = UPLOAD_DIR . $file;
    if (file_exists($filepath) && $file !== 'index.php' && $file !== '.htaccess') {
        unlink($filepath);
        $message = 'Datei gelöscht: ' . $file;
        $messageType = 'success';
        header('Location: /');
        exit;
    }
}

// Dateiliste
$allFiles = array_diff(scandir(UPLOAD_DIR), ['.', '..', 'index.php', '.htaccess']);
$scriptFiles = array_filter($allFiles, 'isScript');
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Script Server</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
        }
        
        h1 {
            color: #2a5298;
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #666;
            font-size: 1.1em;
        }
        
        .content {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .message {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .login-form {
            max-width: 400px;
            margin: 0 auto;
            padding: 30px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }
        
        input[type="password"],
        input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input[type="password"]:focus,
        input[type="file"]:focus {
            outline: none;
            border-color: #2a5298;
        }
        
        button {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .logout-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            background: #dc3545;
            padding: 8px 20px;
            font-size: 14px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            border: 2px solid #e9ecef;
        }
        
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #2a5298;
        }
        
        .stat-label {
            color: #666;
            margin-top: 5px;
        }
        
        .upload-area {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            border: 2px dashed #ddd;
        }
        
        .file-list {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid #dee2e6;
        }
        
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #f1f3f5;
            transition: background 0.2s;
        }
        
        .file-item:hover {
            background: #f8f9fa;
        }
        
        .file-item:last-child {
            border-bottom: none;
        }
        
        .file-name {
            font-family: 'Courier New', monospace;
            font-weight: 500;
            color: #2a5298;
            text-decoration: none;
        }
        
        .file-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .file-size {
            color: #666;
            font-size: 0.9em;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
        }
        
        .btn-small {
            padding: 5px 15px;
            font-size: 14px;
            border-radius: 3px;
            border: none;
            cursor: pointer;
            transition: opacity 0.2s;
        }
        
        .btn-small:hover {
            opacity: 0.8;
        }
        
        .btn-copy {
            background: #28a745;
            color: white;
        }
        
        .btn-delete {
            background: #dc3545;
            color: white;
        }
        
        .btn-download {
            background: #007bff;
            color: white;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            margin-top: 10px;
            word-break: break-all;
            font-size: 0.9em;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            color: #999;
        }
        
        h2 {
            color: #2a5298;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e9ecef;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            header, .content {
                padding: 20px;
            }
            
            h1 {
                font-size: 1.8em;
            }
            
            .stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <?php if (isset($_SESSION['authenticated'])): ?>
                <a href="?logout" class="logout-btn">Logout</a>
            <?php endif; ?>
            <h1>📜 Script Server</h1>
            <p class="subtitle">Host und verwalte Shell-Scripts</p>
        </header>
        
        <div class="content">
            <?php if ($message): ?>
                <div class="message <?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
            <?php endif; ?>
            
            <?php if (!isset($_SESSION['authenticated'])): ?>
                <!-- Login Form -->
                <div class="login-form">
                    <h2>🔐 Admin Login</h2>
                    <form method="post">
                        <input type="hidden" name="action" value="login">
                        <div class="form-group">
                            <label for="password">Passwort:</label>
                            <input type="password" id="password" name="password" required autofocus>
                        </div>
                        <button type="submit">Einloggen</button>
                    </form>
                </div>
                
                <!-- Öffentliche Script-Liste -->
                <?php if (count($scriptFiles) > 0): ?>
                    <h2 style="margin-top: 40px;">📁 Verfügbare Scripts</h2>
                    <div class="file-list">
                        <?php foreach ($scriptFiles as $file): ?>
                            <?php $filepath = UPLOAD_DIR . $file; ?>
                            <div class="file-item">
                                <div>
                                    <a href="/<?= htmlspecialchars($file) ?>" class="file-name" target="_blank">
                                        <?= htmlspecialchars($file) ?>
                                    </a>
                                    <div class="code-block">
                                        curl -sO http://<?= $_SERVER['HTTP_HOST'] ?>/<?= htmlspecialchars($file) ?> && bash <?= htmlspecialchars($file) ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
            <?php else: ?>
                <!-- Admin View -->
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-number"><?= count($scriptFiles) ?></div>
                        <div class="stat-label">Scripts</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?= count($allFiles) ?></div>
                        <div class="stat-label">Gesamt Dateien</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">
                            <?php
                            $totalSize = 0;
                            foreach ($allFiles as $file) {
                                $totalSize += filesize(UPLOAD_DIR . $file);
                            }
                            echo formatSize($totalSize);
                            ?>
                        </div>
                        <div class="stat-label">Speicherplatz</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?= date('H:i') ?></div>
                        <div class="stat-label">Server Zeit</div>
                    </div>
                </div>
                
                <!-- Upload Form -->
                <div class="upload-area">
                    <h2>📤 Script Upload</h2>
                    <form method="post" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="upload">Datei auswählen:</label>
                            <input type="file" id="upload" name="upload" accept=".sh,.bash,.zsh,.py,.pl,.rb,.ps1" required>
                        </div>
                        <button type="submit">Script hochladen</button>
                    </form>
                </div>
                
                <!-- File Management -->
                <h2>📁 Script Verwaltung</h2>
                <?php if (count($allFiles) > 0): ?>
                    <div class="file-list">
                        <?php foreach ($allFiles as $file): ?>
                            <?php $filepath = UPLOAD_DIR . $file; ?>
                            <div class="file-item">
                                <div class="file-info">
                                    <a href="/<?= htmlspecialchars($file) ?>" class="file-name" target="_blank">
                                        <?= htmlspecialchars($file) ?>
                                    </a>
                                    <span class="file-size"><?= formatSize(filesize($filepath)) ?></span>
                                </div>
                                <div class="btn-group">
                                    <button class="btn-small btn-copy" onclick="copyCommand('<?= htmlspecialchars($file) ?>')">
                                        📋 Copy
                                    </button>
                                    <a href="/<?= htmlspecialchars($file) ?>" download class="btn-small btn-download">
                                        💾 Download
                                    </a>
                                    <a href="?delete=<?= urlencode($file) ?>" 
                                       class="btn-small btn-delete"
                                       onclick="return confirm('Wirklich löschen: <?= htmlspecialchars($file) ?>?')">
                                        🗑️ Löschen
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <h3>Keine Dateien vorhanden</h3>
                        <p>Lade dein erstes Script hoch!</p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        function copyCommand(filename) {
            const command = `curl -sO http://<?= $_SERVER['HTTP_HOST'] ?>/${filename} && bash ${filename}`;
            
            // Moderne Clipboard API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(command).then(() => {
                    showNotification('✅ Command kopiert!');
                });
            } else {
                // Fallback für ältere Browser
                const textarea = document.createElement('textarea');
                textarea.value = command;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showNotification('✅ Command kopiert!');
            }
        }
        
        function showNotification(message) {
            const notification = document.createElement('div');
            notification.textContent = message;
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 15px 25px;
                border-radius: 5px;
                box-shadow: 0 5px 15px rgba(0,0,0,0.2);
                z-index: 1000;
                animation: slideIn 0.3s ease;
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => document.body.removeChild(notification), 300);
            }, 3000);
        }
        
        // CSS Animationen
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
PHP_CODE

# Passwort-Hash in PHP einfügen
sed -i "s|PASSWORD_HASH_PLACEHOLDER|$PASS_HASH|g" $SCRIPT_DIR/index.php

# Beispiel-Scripts erstellen
log_step "Erstelle Beispiel-Scripts..."

cat > $SCRIPT_DIR/hello.sh << 'SCRIPT_END'
#!/bin/bash
echo "==================================="
echo "   Hello from Script Server!"
echo "==================================="
echo "Hostname: $(hostname)"
echo "Date: $(date)"
echo "User: $USER"
echo "==================================="
SCRIPT_END

cat > $SCRIPT_DIR/sysinfo.sh << 'SCRIPT_END'
#!/bin/bash
echo "==================================="
echo "       SYSTEM INFORMATION"
echo "==================================="
echo "OS: $(lsb_release -ds 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)"
echo "Kernel: $(uname -r)"
echo "Uptime: $(uptime -p)"
echo "-----------------------------------"
echo "CPU: $(lscpu | grep "Model name" | cut -d':' -f2 | xargs)"
echo "Cores: $(nproc)"
echo "Load: $(cat /proc/loadavg | awk '{print $1, $2, $3}')"
echo "-----------------------------------"
echo "Memory: $(free -h | grep Mem | awk '{print "Total:", $2, "| Used:", $3, "| Free:", $4}')"
echo "Swap: $(free -h | grep Swap | awk '{print "Total:", $2, "| Used:", $3}')"
echo "-----------------------------------"
echo "Disk Usage:"
df -h / | tail -1 | awk '{print "  Root: Total:", $2, "| Used:", $3, "| Free:", $4, "| Usage:", $5}'
echo "==================================="
SCRIPT_END

cat > $SCRIPT_DIR/quick-install.sh << 'SCRIPT_END'
#!/bin/bash
# Quick Install Helper
set -e

show_menu() {
    clear
    echo "==================================="
    echo "     QUICK INSTALL HELPER"
    echo "==================================="
    echo "1) Update System"
    echo "2) Install Docker"
    echo "3) Install Docker Compose"
    echo "4) Install Git"
    echo "5) Install Python3 + pip"
    echo "6) Install Node.js (via NodeSource)"
    echo "7) Install Basic Tools (curl, wget, vim, htop)"
    echo "8) Exit"
    echo "==================================="
    read -p "Select option [1-8]: " choice
    
    case $choice in
        1)
            echo "Updating system..."
            sudo apt update && sudo apt upgrade -y
            echo "System updated!"
            ;;
        2)
            echo "Installing Docker..."
            curl -fsSL https://get.docker.com | sudo bash
            sudo usermod -aG docker $USER
            echo "Docker installed! Please re-login for group changes."
            ;;
        3)
            echo "Installing Docker Compose..."
            sudo apt install -y docker-compose
            echo "Docker Compose installed!"
            ;;
        4)
            echo "Installing Git..."
            sudo apt install -y git
            echo "Git installed!"
            ;;
        5)
            echo "Installing Python3 + pip..."
            sudo apt install -y python3 python3-pip python3-venv
            echo "Python3 installed!"
            ;;
        6)
            echo "Installing Node.js..."
            curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
            sudo apt install -y nodejs
            echo "Node.js installed!"
            ;;
        7)
            echo "Installing basic tools..."
            sudo apt install -y curl wget vim htop net-tools
            echo "Basic tools installed!"
            ;;
        8)
            echo "Goodbye!"
            exit 0
            ;;
        *)
            echo "Invalid option!"
            ;;
    esac
    
    read -p "Press Enter to continue..."
}

# Main loop
while true; do
    show_menu
done
SCRIPT_END

# NEU: PHP Script-Viewer für garantierte Text-Anzeige
log_step "Erstelle Script-Viewer für SSL/Proxy Kompatibilität..."

cat > $SCRIPT_DIR/view.php << 'VIEW_PHP'
<?php
// Script Viewer - garantiert text/plain Ausgabe
$file = $_GET['file'] ?? '';
$file = basename($file); // Sicherheit: nur Dateiname, kein Pfad

// Erlaubte Erweiterungen
$allowed_extensions = ['sh', 'bash', 'zsh', 'py', 'pl', 'rb', 'ps1'];
$file_extension = pathinfo($file, PATHINFO_EXTENSION);

if (empty($file)) {
    // Zeige Liste aller Scripts
    header('Content-Type: text/plain; charset=utf-8');
    echo "Available scripts:\n\n";
    foreach (glob(__DIR__ . '/*.{sh,bash,zsh,py,pl,rb,ps1}', GLOB_BRACE) as $script) {
        $name = basename($script);
        echo "  • $name\n";
        echo "    curl -s https://\$YOUR_DOMAIN/view.php?file=$name | bash\n\n";
    }
    exit;
}

$filepath = __DIR__ . '/' . $file;

// Sicherheitschecks
if (!file_exists($filepath)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    die("Error: Script '$file' not found\n");
}

if (!in_array($file_extension, $allowed_extensions)) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    die("Error: File type not allowed\n");
}

// Ausgabe als reiner Text - IMMER
header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: inline; filename="' . $file . '"');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-cache, must-revalidate');

// Script ausgeben
readfile($filepath);
VIEW_PHP

# .htaccess für Apache-Kompatibilität (falls jemand Apache nutzt)
cat > $SCRIPT_DIR/.htaccess << 'HTACCESS'
<FilesMatch "\.(sh|bash|zsh|py|pl|rb|ps1)$">
    ForceType text/plain
    Header set Content-Type "text/plain; charset=utf-8"
    Header set Content-Disposition "inline"
    Header set X-Content-Type-Options "nosniff"
</FilesMatch>
HTACCESS

# Berechtigungen setzen
chmod 644 $SCRIPT_DIR/*.sh
chmod 644 $SCRIPT_DIR/*.php
chown -R www-data:www-data $SCRIPT_DIR

# Services konfigurieren und starten
log_step "Starte Services..."

# PHP-FPM
systemctl restart php${PHP_VERSION}-fpm
systemctl enable php${PHP_VERSION}-fpm

# Nginx testen und neu laden
nginx -t
if [ $? -eq 0 ]; then
    systemctl restart nginx
    systemctl enable nginx
else
    log_error "Nginx Konfiguration fehlerhaft!"
    exit 1
fi

# Firewall (falls vorhanden)
if command -v ufw &> /dev/null; then
    log_step "Konfiguriere Firewall..."
    ufw allow $PORT/tcp
    ufw allow 22/tcp
fi

# Test ob Server erreichbar ist
log_step "Teste Server..."
sleep 2
if curl -s -o /dev/null -w "%{http_code}" http://localhost:$PORT/ | grep -q "200"; then
    log_info "✅ Server läuft!"
else
    log_warn "⚠️  Server-Test fehlgeschlagen"
fi

# Test ob Scripts als text/plain ausgeliefert werden
log_step "Teste Content-Type für Scripts..."
CONTENT_TYPE=$(curl -s -I http://localhost:$PORT/hello.sh | grep -i "content-type:" | cut -d' ' -f2)
if echo "$CONTENT_TYPE" | grep -q "text/plain"; then
    log_info "✅ Scripts werden korrekt als text/plain ausgeliefert"
else
    log_warn "⚠️  Content-Type Test fehlgeschlagen: $CONTENT_TYPE"
fi

# Abschluss
clear
cat << EOF
╔═══════════════════════════════════════════════════════════╗
║                   INSTALLATION ERFOLGREICH!                ║
╚═══════════════════════════════════════════════════════════╝

  🌐 Web-Interface:   http://$SERVER_IP/
  
  🔑 Admin Login:
     Passwort:       $ADMIN_PASSWORD
  
  📁 Script-Verzeichnis: $SCRIPT_DIR
  
  📋 Test-Befehle:
     
     Direkt (kann Probleme mit SSL haben):
     curl -s http://$SERVER_IP/hello.sh | bash
     
     EMPFOHLEN für SSL/Proxy (funktioniert IMMER):
     curl -s http://$SERVER_IP/view.php?file=hello.sh | bash
     curl -s https://deine-domain.de/view.php?file=hello.sh | bash
  
  📤 Scripts hinzufügen:
     - Via Web-Interface (nach Login)
     - Via SCP: scp script.sh root@$SERVER_IP:$SCRIPT_DIR/
  
  📊 Logs:
     tail -f /var/log/nginx/script-server.error.log

═══════════════════════════════════════════════════════════
  ⚠️  WICHTIG: 
  - Speichere das Admin-Passwort sicher!
  - Bei SSL/Proxy: Nutze /view.php?file=SCRIPTNAME
═══════════════════════════════════════════════════════════

EOF

# Passwort nochmal in Datei speichern
echo "Admin-Passwort: $ADMIN_PASSWORD" > /root/script-server-credentials.txt
chmod 600 /root/script-server-credentials.txt
log_info "Credentials gespeichert in: /root/script-server-credentials.txt"