#Requires -RunAsAdministrator
$ErrorActionPreference = "Continue"
$ProgressPreference = "SilentlyContinue"

$tempDir = "$env:TEMP\vserver-setup"
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  VServer Setup - Automatische Installation" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

function Download-File {
    param($Url, $Output)
    Write-Host "  Downloading: $Output" -ForegroundColor Gray
    try {
        $webClient = New-Object System.Net.WebClient
        $webClient.Headers.Add("User-Agent", "Mozilla/5.0")
        $webClient.DownloadFile($Url, $Output)
        return $true
    } catch {
        Write-Host "  FEHLER beim Download: $_" -ForegroundColor Red
        return $false
    }
}

# 1. PYTHON
Write-Host "[1/12] Python..." -ForegroundColor Yellow
$pythonInstalled = (Get-Command python -ErrorAction SilentlyContinue) -or (Test-Path "C:\Program Files\Python*\python.exe")
if ($pythonInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $pythonUrl = "https://www.python.org/ftp/python/3.12.4/python-3.12.4-amd64.exe"
    $pythonInstaller = "$tempDir\python-installer.exe"
    if (Download-File -Url $pythonUrl -Output $pythonInstaller) {
        Write-Host "  Installiere Python (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $pythonInstaller -ArgumentList "/quiet", "InstallAllUsers=1", "PrependPath=1", "Include_pip=1" -Wait
        Write-Host "  Python installiert!" -ForegroundColor Green
    }
}

# 2. FFMPEG
Write-Host "[2/12] FFmpeg..." -ForegroundColor Yellow
if (Test-Path "C:\ffmpeg\bin\ffmpeg.exe") {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $ffmpegUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
    $ffmpegZip = "$tempDir\ffmpeg.zip"
    if (Download-File -Url $ffmpegUrl -Output $ffmpegZip) {
        Write-Host "  Entpacke FFmpeg nach C:\ffmpeg..." -ForegroundColor Gray
        if (Test-Path "C:\ffmpeg") { Remove-Item -Path "C:\ffmpeg" -Recurse -Force }
        Expand-Archive -Path $ffmpegZip -DestinationPath $tempDir -Force
        $ffmpegExtracted = Get-ChildItem -Path $tempDir -Directory | Where-Object { $_.Name -like "ffmpeg-*" } | Select-Object -First 1
        if ($ffmpegExtracted) {
            Move-Item -Path $ffmpegExtracted.FullName -Destination "C:\ffmpeg" -Force
            Write-Host "  FFmpeg entpackt!" -ForegroundColor Green
        }
    }
}
$currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
if ($currentPath -notlike "*C:\ffmpeg\bin*") {
    Write-Host "  Setze PATH Variable..." -ForegroundColor Gray
    [Environment]::SetEnvironmentVariable("Path", "$currentPath;C:\ffmpeg\bin", "Machine")
    Write-Host "  PATH aktualisiert!" -ForegroundColor Green
}

# 3. WINRAR
Write-Host "[3/12] WinRAR..." -ForegroundColor Yellow
if (Test-Path "C:\Program Files\WinRAR\WinRAR.exe") {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $winrarUrl = "https://www.win-rar.com/fileadmin/winrar-versions/winrar/winrar-x64-701.exe"
    $winrarInstaller = "$tempDir\winrar-installer.exe"
    if (Download-File -Url $winrarUrl -Output $winrarInstaller) {
        Write-Host "  Installiere WinRAR (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $winrarInstaller -ArgumentList "/S" -Wait
        Write-Host "  WinRAR installiert!" -ForegroundColor Green
    }
}

# 4. G-EARTH (nach WinRAR, damit wir entpacken koennen)
Write-Host "[4/12] G-Earth..." -ForegroundColor Yellow
$gearthPath = "$([Environment]::GetFolderPath('Desktop'))\G-Earth"
if (Test-Path $gearthPath) {
    Write-Host "  Bereits vorhanden - ueberspringe." -ForegroundColor Gray
} else {
    $gearthUrl = "https://streamerware.de/G-earth.rar"
    $gearthRar = "$tempDir\G-earth.rar"
    if (Download-File -Url $gearthUrl -Output $gearthRar) {
        Write-Host "  Entpacke G-Earth auf Desktop..." -ForegroundColor Gray
        $winrarPath = "C:\Program Files\WinRAR\WinRAR.exe"
        if (Test-Path $winrarPath) {
            Start-Process -FilePath $winrarPath -ArgumentList "x", "-ibck", "-o+", $gearthRar, "$([Environment]::GetFolderPath('Desktop'))\" -Wait
            Write-Host "  G-Earth installiert!" -ForegroundColor Green
        } else {
            Write-Host "  FEHLER: WinRAR nicht gefunden" -ForegroundColor Red
        }
    }
}

# 5. VLC
Write-Host "[5/12] VLC..." -ForegroundColor Yellow
if (Test-Path "C:\Program Files\VideoLAN\VLC\vlc.exe") {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $vlcUrl = "https://ftp.fau.de/videolan/vlc/3.0.21/win64/vlc-3.0.21-win64.exe"
    $vlcInstaller = "$tempDir\vlc-installer.exe"
    if (Download-File -Url $vlcUrl -Output $vlcInstaller) {
        Write-Host "  Installiere VLC (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $vlcInstaller -ArgumentList "/S", "/L=1031" -Wait
        Write-Host "  VLC installiert!" -ForegroundColor Green
    }
}

# 5. JAVA 8
Write-Host "[6/12] Java 8..." -ForegroundColor Yellow
$javaInstalled = (Test-Path "C:\Program Files\Java\*") -or (Test-Path "C:\Program Files\Eclipse Adoptium\*") -or (Get-Command java -ErrorAction SilentlyContinue)
if ($javaInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $javaUrl = "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u432-b06/OpenJDK8U-jre_x64_windows_hotspot_8u432b06.msi"
    $javaInstaller = "$tempDir\java8.msi"
    if (Download-File -Url $javaUrl -Output $javaInstaller) {
        Write-Host "  Installiere Java 8 (silent)..." -ForegroundColor Gray
        Start-Process -FilePath "msiexec.exe" -ArgumentList "/i", $javaInstaller, "/quiet", "/norestart" -Wait
        Write-Host "  Java 8 installiert!" -ForegroundColor Green
    }
}

# 6. .NET FRAMEWORK 4.8
Write-Host "[7/13] .NET Framework 4.8..." -ForegroundColor Yellow
$netInstalled = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" -ErrorAction SilentlyContinue).Release -ge 528040
if ($netInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $netUrl = "https://go.microsoft.com/fwlink/?linkid=2088631"
    $netInstaller = "$tempDir\dotnet48.exe"
    if (Download-File -Url $netUrl -Output $netInstaller) {
        Write-Host "  Installiere .NET Framework 4.8 (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $netInstaller -ArgumentList "/q", "/norestart" -Wait
        Write-Host "  .NET Framework 4.8 installiert!" -ForegroundColor Green
    }
}

# 7. .NET 6.0 DESKTOP RUNTIME
Write-Host "[8/13] .NET 6.0 Desktop Runtime..." -ForegroundColor Yellow
$net6Installed = (Test-Path "C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\6.*") -or (Test-Path "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.*")
if ($net6Installed) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $net6Url = "https://streamerware.de/windowsdesktop-runtime-6.0.36-win-x64.exe"
    $net6Installer = "$tempDir\dotnet6-desktop.exe"
    if (Download-File -Url $net6Url -Output $net6Installer) {
        Write-Host "  Installiere .NET 6.0 Desktop Runtime (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $net6Installer -ArgumentList "/install", "/quiet", "/norestart" -Wait
        Write-Host "  .NET 6.0 Desktop Runtime installiert!" -ForegroundColor Green
    }
}

# 9. .NET 8.0 DESKTOP RUNTIME
Write-Host "[9/16] .NET 8.0 Desktop Runtime..." -ForegroundColor Yellow
$net8Installed = (Test-Path "C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.*") -or (Test-Path "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.*")
if ($net8Installed) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $net8Url = "https://streamerware.de/windowsdesktop-runtime-8.0.23-win-x64.exe"
    $net8Installer = "$tempDir\dotnet8-desktop.exe"
    if (Download-File -Url $net8Url -Output $net8Installer) {
        Write-Host "  Installiere .NET 8.0 Desktop Runtime (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $net8Installer -ArgumentList "/install", "/quiet", "/norestart" -Wait
        Write-Host "  .NET 8.0 Desktop Runtime installiert!" -ForegroundColor Green
    }
}

# 10. GOOGLE CHROME
Write-Host "[10/16] Google Chrome..." -ForegroundColor Yellow
$chromeInstalled = (Test-Path "C:\Program Files\Google\Chrome\Application\chrome.exe") -or (Test-Path "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
if ($chromeInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $chromeUrl = "https://dl.google.com/chrome/install/latest/chrome_installer.exe"
    $chromeInstaller = "$tempDir\chrome_installer.exe"
    if (Download-File -Url $chromeUrl -Output $chromeInstaller) {
        Write-Host "  Installiere Google Chrome (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $chromeInstaller -ArgumentList "/silent", "/install" -Wait
        Write-Host "  Google Chrome installiert!" -ForegroundColor Green
    }
}

# 10. HABBO LAUNCHER
Write-Host "[11/16] Habbo Launcher..." -ForegroundColor Yellow
$habboInstalled = (Test-Path "$env:LOCALAPPDATA\Programs\habbo-launcher\Habbo Launcher.exe") -or (Test-Path "C:\Program Files\Habbo Launcher\*") -or (Test-Path "$env:USERPROFILE\AppData\Local\Programs\habbo-launcher\Habbo Launcher.exe") -or (Get-ChildItem "C:\Users\*\AppData\Local\Programs\habbo-launcher\Habbo Launcher.exe" -ErrorAction SilentlyContinue) -or (Test-Path "$([Environment]::GetFolderPath('Desktop'))\Habbo Launcher.lnk")
if ($habboInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $habboUrl = "https://streamerware.de/HabboLauncher-Setup-1.0.80.exe"
    $habboInstaller = "$tempDir\HabboLauncher-Setup.exe"
    if (Download-File -Url $habboUrl -Output $habboInstaller) {
        Write-Host "  Installiere Habbo Launcher (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $habboInstaller -ArgumentList "/S" -Wait
        Write-Host "  Habbo Launcher installiert!" -ForegroundColor Green
    }
}

# 8. JDOWNLOADER (von Website laden)
Write-Host "[12/16] JDownloader..." -ForegroundColor Yellow
$jdPath = "$env:LOCALAPPDATA\JDownloader 2.0"
$jdInstalled = (Test-Path "$jdPath\JDownloader2.exe") -or (Test-Path "C:\Program Files\JDownloader\JDownloader2.exe")
if ($jdInstalled) {
    Write-Host "  Bereits installiert - ueberspringe." -ForegroundColor Gray
} else {
    $jdUrl = "http://streamerware.de/JDownloader2Setup_windows-amd64_v21_0_7.exe"
    $jdInstaller = "$tempDir\JDownloader2Setup.exe"
    if (Download-File -Url $jdUrl -Output $jdInstaller) {
        Write-Host "  Installiere JDownloader (silent)..." -ForegroundColor Gray
        Start-Process -FilePath $jdInstaller -ArgumentList "-q" -Wait
        Write-Host "  JDownloader installiert!" -ForegroundColor Green
    }
}

# JD2 BACKUP IMPORTIEREN (eingebettet)
$jdPaths = @(
    "$env:LOCALAPPDATA\JDownloader 2.0",
    "C:\Program Files\JDownloader",
    "C:\Users\Administrator\AppData\Local\JDownloader 2.0"
)
$jdPath = $null
foreach ($p in $jdPaths) {
    if (Test-Path $p) { $jdPath = $p; break }
}
# Pruefen ob Backup bereits importiert wurde (cfg Ordner existiert)
if ($jdPath -and (Test-Path "$jdPath\cfg")) {
    Write-Host "  JD2-Backup bereits importiert - ueberspringe." -ForegroundColor Gray
} elseif ($jdPath) {
    Write-Host "  Importiere JD2-Backup..." -ForegroundColor Cyan
    Write-Host "  Ziel: $jdPath" -ForegroundColor Gray
    # JD2 Backup wird als separate Datei mitgeliefert (jdownloader-backup.zip)
    # oder aus dem gleichen Verzeichnis wie das Script geladen
    $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
    $backupZip = Join-Path $scriptDir "jdownloader-backup.zip"
    if (-not (Test-Path $backupZip)) {
        $backupZip = "$tempDir\jd2backup.zip"
        $backupUrl = "https://streamerware.de/jdownloader-backup.zip"
        Download-File -Url $backupUrl -Output $backupZip | Out-Null
    }
    try {
        Expand-Archive -Path $backupZip -DestinationPath $jdPath -Force
        Write-Host "  JD2-Settings importiert!" -ForegroundColor Green
    } catch {
        Write-Host "  FEHLER beim Import: $_" -ForegroundColor Red
    }
} else {
    Write-Host "  JDownloader-Ordner nicht gefunden - Backup uebersprungen" -ForegroundColor Yellow
}

# 6. FILE-UPLOADER + ORDNER
Write-Host ""
Write-Host "[13/16] Desktop Ordner..." -ForegroundColor Yellow
$desktopPath = [Environment]::GetFolderPath("Desktop")

# Ordner "Fertig" und "Unfertig" erstellen (nur wenn nicht vorhanden)
if (Test-Path "$desktopPath\Fertig") {
    Write-Host "  Ordner 'Fertig' bereits vorhanden." -ForegroundColor Gray
} else {
    Write-Host "  Erstelle Ordner 'Fertig'..." -ForegroundColor Gray
    New-Item -ItemType Directory -Force -Path "$desktopPath\Fertig" | Out-Null
}
if (Test-Path "$desktopPath\Unfertig") {
    Write-Host "  Ordner 'Unfertig' bereits vorhanden." -ForegroundColor Gray
} else {
    Write-Host "  Erstelle Ordner 'Unfertig'..." -ForegroundColor Gray
    New-Item -ItemType Directory -Force -Path "$desktopPath\Unfertig" | Out-Null
}

# File-Uploader vom Server laden (nur wenn nicht vorhanden)
if (Test-Path "$desktopPath\File-Uploader") {
    Write-Host "  File-Uploader bereits vorhanden - ueberspringe." -ForegroundColor Gray
} else {
    Write-Host "  Lade File-Uploader vom Server..." -ForegroundColor Gray
    $fileUploaderUrl = "https://streamerware.de/FileUploader.rar"
    $uploaderRar = "$tempDir\FileUploader.rar"

    if (Download-File -Url $fileUploaderUrl -Output $uploaderRar) {
        try {
            $winrarPath = "C:\Program Files\WinRAR\WinRAR.exe"
            if (Test-Path $winrarPath) {
                Start-Process -FilePath $winrarPath -ArgumentList "x", "-ibck", "-o+", $uploaderRar, "$desktopPath\" -Wait
                Write-Host "  File-Uploader installiert!" -ForegroundColor Green
            } else {
                Write-Host "  FEHLER: WinRAR nicht gefunden (fuer .rar Entpacken)." -ForegroundColor Red
            }
        } catch {
            Write-Host "  FEHLER beim Entpacken: $_" -ForegroundColor Red
        }
    } else {
        Write-Host "  FEHLER: Download vom Server fehlgeschlagen." -ForegroundColor Red
    }
}

Write-Host "  Desktop Ordner erstellt!" -ForegroundColor Green

# 13. SCRIPTE
Write-Host ""
Write-Host "[14/16] Scripte..." -ForegroundColor Yellow
if (Test-Path "$desktopPath\Rename MKV AVI.py") {
    Write-Host "  Bereits vorhanden - ueberspringe." -ForegroundColor Gray
} else {
    $scripteUrl = "https://streamerware.de/Scripte.rar"
    $scripteRar = "$tempDir\Scripte.rar"
    if (Download-File -Url $scripteUrl -Output $scripteRar) {
        Write-Host "  Entpacke Scripte auf Desktop..." -ForegroundColor Gray
        $winrarPath = "C:\Program Files\WinRAR\WinRAR.exe"
        if (Test-Path $winrarPath) {
            Start-Process -FilePath $winrarPath -ArgumentList "x", "-ibck", "-o+", $scripteRar, "$desktopPath\" -Wait
            Write-Host "  Scripte installiert!" -ForegroundColor Green
        } else {
            Write-Host "  FEHLER: WinRAR nicht gefunden" -ForegroundColor Red
        }
    }
}

# 14. TWITCH VOD MANAGER
Write-Host ""
Write-Host "[15/16] Twitch VOD Manager..." -ForegroundColor Yellow
$twitchPath = "$desktopPath\Twitch Downloader"
if (Test-Path "$twitchPath\Twitch_VOD_Manager.exe") {
    Write-Host "  Bereits vorhanden - ueberspringe." -ForegroundColor Gray
} else {
    $twitchUrl = "https://streamerware.de/Twitch_VOD_Manager.zip"
    $twitchZip = "$tempDir\Twitch_VOD_Manager.zip"
    if (Download-File -Url $twitchUrl -Output $twitchZip) {
        Write-Host "  Entpacke Twitch VOD Manager auf Desktop..." -ForegroundColor Gray
        Expand-Archive -Path $twitchZip -DestinationPath $desktopPath -Force
        Write-Host "  Twitch VOD Manager installiert!" -ForegroundColor Green
    }
}

# 12. WINDOWS EINSTELLUNGEN
Write-Host ""
Write-Host "[16/16] Windows Einstellungen..." -ForegroundColor Yellow

# IE Enhanced Security Configuration deaktivieren (fuer Administratoren und Benutzer)
Write-Host "  IE Enhanced Security deaktivieren..." -ForegroundColor Gray
$ieAdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
$ieUserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
if (Test-Path $ieAdminKey) {
    Set-ItemProperty -Path $ieAdminKey -Name "IsInstalled" -Value 0 -Type DWord -Force
}
if (Test-Path $ieUserKey) {
    Set-ItemProperty -Path $ieUserKey -Name "IsInstalled" -Value 0 -Type DWord -Force
}

# Taskansicht-Schaltflaeche ausblenden
Write-Host "  Taskansicht-Button ausblenden..." -ForegroundColor Gray
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Value 0 -Type DWord -Force

# Suchfeld ausblenden
Write-Host "  Suchfeld ausblenden..." -ForegroundColor Gray
if (-not (Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search")) {
    New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" -Force | Out-Null
}
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" -Value 0 -Type DWord -Force

# Desktop kleine Symbole
Write-Host "  Desktop auf kleine Symbole..." -ForegroundColor Gray
$desktopRegPath = "HKCU:\SOFTWARE\Microsoft\Windows\Shell\Bags\1\Desktop"
if (-not (Test-Path $desktopRegPath)) {
    New-Item -Path $desktopRegPath -Force | Out-Null
}
Set-ItemProperty -Path $desktopRegPath -Name "IconSize" -Value 32 -Type DWord -Force
Set-ItemProperty -Path $desktopRegPath -Name "Mode" -Value 1 -Type DWord -Force
Set-ItemProperty -Path $desktopRegPath -Name "LogicalViewMode" -Value 3 -Type DWord -Force

Write-Host "  Windows Einstellungen angepasst!" -ForegroundColor Green

# CLEANUP
Write-Host ""
Write-Host "Raeume auf..." -ForegroundColor Gray
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "  FERTIG! Alle Programme installiert." -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Druecke eine Taste zum Beenden..."