$ErrorActionPreference = 'Continue'
$svc = Get-Service -Name 'Syncro','SyncroLive','SyncroOvermind' -ErrorAction SilentlyContinue
if ($svc) {
    $names = ($svc | ForEach-Object { $_.Name + '=' + $_.Status }) -join ','
    Write-Output ('SYNCRO-ALREADY-INSTALLED services=[' + $names + ']')
    exit 0
}
# Clean any leftover from prior failed installs
$repairDir = 'C:\Program Files\RepairTech'
if (Test-Path $repairDir) {
    Remove-Item $repairDir -Recurse -Force -ErrorAction SilentlyContinue
    Write-Output 'CLEANED prior RepairTech directory'
}
foreach ($k in @('HKLM:\SOFTWARE\WOW6432Node\RepairTech\Syncro','HKLM:\SOFTWARE\WOW6432Node\RepairTech\Kabuto')) {
    if (Test-Path $k) { Remove-Item $k -Recurse -Force -ErrorAction SilentlyContinue; Write-Output ("CLEANED registry: $k") }
}
$msi = 'C:\Windows\Temp\SyncroSetup-khalsa.msi'
if (-not (Test-Path $msi)) {
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072
    (New-Object Net.WebClient).DownloadFile('https://rmm.syncromsp.com/dl/msi/djEtOTQ1NjU1NC0xNTA3NjA4MzYxLTQ4NzUzLTM2ODUwMjI=', $msi)
    Write-Output ('MSI downloaded ' + [math]::Round((Get-Item $msi).Length / 1MB, 1) + ' MB')
} else {
    Write-Output ('MSI already present ' + [math]::Round((Get-Item $msi).Length / 1MB, 1) + ' MB')
}
$log = 'C:\Windows\Temp\syncro-install-final.log'
$p = Start-Process msiexec.exe -ArgumentList '/i', $msi, '/qn', '/norestart', '/L*v', $log -Wait -PassThru
Write-Output ('msiexec exit=' + $p.ExitCode)
if ($p.ExitCode -eq 0) {
    Start-Sleep -Seconds 30
    $svc2 = Get-Service -Name 'Syncro','SyncroLive','SyncroOvermind' -ErrorAction SilentlyContinue
    if ($svc2) {
        Write-Output ('SYNCRO-INSTALL-OK ' + (($svc2 | ForEach-Object { $_.Name + '=' + $_.Status }) -join ','))
    } else {
        Write-Output 'SYNCRO-SERVICES-NOT-YET-VISIBLE - may need a moment to register'
    }
} else {
    Write-Output '--- last 30 lines of install log ---'
    if (Test-Path $log) { Get-Content $log -Tail 30 }
    Write-Output '--- Return value 3 context ---'
    if (Test-Path $log) {
        $lines = Get-Content $log
        $idx = ($lines | Select-String 'Return value 3' | Select-Object -First 1).LineNumber
        if ($idx) { $lines[[math]::Max(0, $idx - 10)..[math]::Min($lines.Count - 1, $idx + 2)] | Write-Output }
    }
}
Remove-Item $msi -Force -ErrorAction SilentlyContinue
