$ErrorActionPreference = "Stop"

$SourceDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$InstallDir = Join-Path $env:LOCALAPPDATA "Programs\LunaTunnel"
$DataDir = Join-Path $env:LOCALAPPDATA "LunaTunnel"
$ExtensionDir = Join-Path $InstallDir "Extension"
$HostManifestPath = Join-Path $DataDir "native-host.json"
$ExtensionOrigin = "chrome-extension://mmkiehpiobigepeojcjdppjcklfppmij/"
$Version = "0.1.2"

if (-not (Test-Path (Join-Path $SourceDir "LunaTunnelCore.exe"))) {
    throw "LunaTunnelCore.exe was not found. Extract the complete archive first."
}
if (-not (Test-Path (Join-Path $SourceDir "sing-box.exe"))) {
    throw "sing-box.exe was not found. Extract the complete archive first."
}
if (-not (Test-Path (Join-Path $SourceDir "sing-box-xhttp.exe"))) {
    throw "sing-box-xhttp.exe was not found. Extract the complete archive first."
}

# Stop only LunaTunnel components from a previous installation. This makes an
# in-place update reliable and also removes orphaned 0.1.1 processes without
# touching Hiddify or any other VPN client.
Get-CimInstance Win32_Process | Where-Object {
    $_.ExecutablePath -and $_.ExecutablePath.StartsWith($InstallDir, [System.StringComparison]::OrdinalIgnoreCase)
} | ForEach-Object {
    Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
}
Start-Sleep -Milliseconds 350

$InstallRoot = [System.IO.Path]::GetFullPath($InstallDir).TrimEnd('\') + '\'
$ExtensionRoot = [System.IO.Path]::GetFullPath($ExtensionDir)
if (-not $ExtensionRoot.StartsWith($InstallRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw "Unsafe LunaTunnel extension path: $ExtensionRoot"
}
if (Test-Path $ExtensionRoot) {
    Remove-Item -LiteralPath $ExtensionRoot -Recurse -Force
}

New-Item -ItemType Directory -Force -Path $InstallDir, $DataDir | Out-Null
Copy-Item -Force (Join-Path $SourceDir "LunaTunnelCore.exe") $InstallDir
Copy-Item -Force (Join-Path $SourceDir "sing-box.exe") $InstallDir
Copy-Item -Force (Join-Path $SourceDir "sing-box-xhttp.exe") $InstallDir
Copy-Item -Recurse -Force (Join-Path $SourceDir "Extension") $InstallDir
Copy-Item -Force (Join-Path $SourceDir "THIRD_PARTY_NOTICES.md") $InstallDir
if (Test-Path (Join-Path $SourceDir "LICENSE-sing-box.txt")) {
    Copy-Item -Force (Join-Path $SourceDir "LICENSE-sing-box.txt") $InstallDir
}
if (Test-Path (Join-Path $SourceDir "LICENSE-hiddify-sing-box.txt")) {
    Copy-Item -Force (Join-Path $SourceDir "LICENSE-hiddify-sing-box.txt") $InstallDir
}

$HostManifest = [ordered]@{
    name = "run.lunatunnel.core"
    description = "LunaTunnel Browser Native Messaging Host"
    path = (Join-Path $InstallDir "LunaTunnelCore.exe")
    type = "stdio"
    allowed_origins = @($ExtensionOrigin)
}
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($HostManifestPath, ($HostManifest | ConvertTo-Json -Depth 5), $Utf8NoBom)

$ChromeKey = "HKCU:\Software\Google\Chrome\NativeMessagingHosts\run.lunatunnel.core"
$EdgeKey = "HKCU:\Software\Microsoft\Edge\NativeMessagingHosts\run.lunatunnel.core"
New-Item -Force $ChromeKey | Out-Null
Set-Item -Path $ChromeKey -Value $HostManifestPath
New-Item -Force $EdgeKey | Out-Null
Set-Item -Path $EdgeKey -Value $HostManifestPath

Write-Host ""
Write-Host "LunaTunnel Browser $Version is installed." -ForegroundColor Green
Write-Host "Extension directory: $ExtensionDir" -ForegroundColor Cyan
Write-Host ""
Write-Host "In chrome://extensions enable Developer mode, click Load unpacked, and select this directory."
Set-Clipboard -Value $ExtensionDir
Write-Host "The directory path is already in the clipboard." -ForegroundColor Yellow

$Chrome = Get-Command chrome.exe -ErrorAction SilentlyContinue
if ($Chrome) {
    Start-Process $Chrome.Source "chrome://extensions"
} else {
    Start-Process "chrome://extensions"
}
