$ErrorActionPreference = "Stop"

$PackName = "Dimensional Doors Recovery 1.4.7"
$Hostname = "dimdoors.system42.one"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$Instances = Join-Path $env:APPDATA "PrismLauncher\instances"
$Target = Join-Path $Instances $PackName
$Tools = Join-Path $env:LOCALAPPDATA "DimDoorsRecovery"
$Api = "https://api.github.com/repos/PrismLauncher/PrismLauncher/releases/latest"

New-Item -ItemType Directory -Force -Path $Target, $Tools | Out-Null
Get-ChildItem -LiteralPath $ScriptDir -Force | ForEach-Object {
    Copy-Item -LiteralPath $_.FullName -Destination $Target -Recurse -Force
}

$Cloudflared = Join-Path $Tools "cloudflared.exe"
if (!(Test-Path $Cloudflared)) {
    $arch = if ($env:PROCESSOR_ARCHITECTURE -match "ARM64") { "arm64" } else { "amd64" }
    Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-$arch.exe" -OutFile $Cloudflared
}

function Find-PrismLauncher {
    foreach ($root in @($env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:LOCALAPPDATA)) {
        if (!$root) { continue }
        foreach ($candidate in @((Join-Path $root "PrismLauncher\prismlauncher.exe"), (Join-Path $root "Programs\PrismLauncher\prismlauncher.exe"), (Join-Path $root "DimDoorsPrismLauncher\prismlauncher.exe"))) {
            if (Test-Path $candidate) { return $candidate }
        }
    }
    return $null
}

$Launcher = Find-PrismLauncher
if (!$Launcher) {
    $installRoot = Join-Path $env:LOCALAPPDATA "DimDoorsPrismLauncher"
    New-Item -ItemType Directory -Force -Path $installRoot | Out-Null
    $release = Invoke-RestMethod -Uri $Api -Headers @{ "User-Agent" = "DimDoorsRecoveryInstaller" }
    $pattern = if ($env:PROCESSOR_ARCHITECTURE -match "ARM64") { "PrismLauncher-Windows-MinGW-arm64-Portable-*.zip" } else { "PrismLauncher-Windows-MinGW-w64-Portable-*.zip" }
    $asset = $release.assets | Where-Object { $_.name -like $pattern } | Select-Object -First 1
    if (!$asset) { throw "No compatible Prism Launcher portable archive was found." }
    $zip = Join-Path $installRoot $asset.name
    Invoke-WebRequest -UseBasicParsing -Uri $asset.browser_download_url -OutFile $zip
    Expand-Archive -Path $zip -DestinationPath $installRoot -Force
    $Launcher = (Get-ChildItem -Path $installRoot -Recurse -Filter "prismlauncher.exe" | Select-Object -First 1).FullName
}

Get-Process cloudflared -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $Cloudflared } | Stop-Process -Force
Start-Process -WindowStyle Hidden -FilePath $Cloudflared -ArgumentList @("access", "tcp", "--hostname", $Hostname, "--url", "127.0.0.1:25570", "--logfile", (Join-Path $Tools "cloudflared.log"), "--log-level", "info")
Start-Sleep -Seconds 2
Start-Process -FilePath $Launcher -ArgumentList @("-l", $PackName, "-s", "127.0.0.1:25570")
Write-Host "Started $PackName through $Hostname"
