# NetExperts Support Post-Install Script
# Runs after MSI installation to:
# 1. Uninstall "AnyDesk NetExperts Support" if present
# 2. Report installation to NetExperts API

$ErrorActionPreference = "SilentlyContinue"

# --- 1. Uninstall AnyDesk NetExperts Support ---
Write-Host "Checking for AnyDesk NetExperts Support..."

# Search both 64-bit and 32-bit uninstall registry
$adPaths = @(
    "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
    "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
)

foreach ($path in $adPaths) {
    $ad = Get-ItemProperty $path | Where-Object { $_.DisplayName -eq "AnyDesk NetExperts Support" }
    if ($ad) {
        Write-Host "Found AnyDesk NetExperts Support, uninstalling..."
        $productCode = $ad.PSChildName
        Start-Process msiexec -ArgumentList "/x", $productCode, "/quiet", "/norestart" -Wait -NoNewWindow
        Write-Host "AnyDesk NetExperts Support uninstall initiated: $productCode"

        # Also clean up service and files in case MSI uninstall is incomplete
        Stop-Service "AnyDesk-ad_69257027_msi" -Force -ErrorAction SilentlyContinue
        sc.exe delete "AnyDesk-ad_69257027_msi" 2>$null
        Stop-Process -Name "AnyDesk-ad_69257027_msi*" -Force -ErrorAction SilentlyContinue
        Remove-Item "C:\Program Files (x86)\AnyDesk-ad_69257027_msi" -Recurse -Force -ErrorAction SilentlyContinue
        Remove-Item "C:\ProgramData\AnyDesk\ad_69257027_msi" -Recurse -Force -ErrorAction SilentlyContinue
        Write-Host "AnyDesk cleanup complete."
        break
    }
}

# --- 2. Report installation to NetExperts API ---
Write-Host "Reporting installation..."

try {
    $computerName = $env:COMPUTERNAME
    $username = $env:USERNAME
    $ip = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notlike "*Loopback*" -and $_.IPAddress -ne "127.0.0.1" } | Select-Object -First 1).IPAddress
    if (-not $ip) { $ip = "unknown" }

    $body = @{
        computer_name = $computerName
        ip_address = $ip
        username = $username
        version = "1.1.1"
        client_type = "windows"
    } | ConvertTo-Json

    Invoke-RestMethod -Uri "https://support.nxx.au/api/install/report" -Method POST -Body $body -ContentType "application/json" -TimeoutSec 10
    Write-Host "Installation reported successfully."
} catch {
    # Non-fatal - don't block install if reporting fails
    Write-Host "Installation report failed (non-fatal): $_"
}
