param(
  [switch]$TermosAceitos
)

$ErrorActionPreference = "Stop"

if (-not $TermosAceitos) {
  throw "Use AMBROSIA-SETUP.bat e aceite os Termos de Uso antes de instalar ou atualizar."
}

Write-Host ""
Write-Host "AMBROSIA NATIVO PARA WINDOWS - V2.8.4" -ForegroundColor DarkYellow
Write-Host "Criando o programa nativo. Nenhum navegador sera usado." -ForegroundColor Gray

$packageRoot = Split-Path $PSScriptRoot
$sourceFile = Join-Path $packageRoot "AmbrosiaNativo.cs"
$launcherFile = Join-Path $PSScriptRoot "iniciar-nativo.ps1"
$uninstallerFile = Join-Path $PSScriptRoot "desinstalar-nativo.ps1"
$setupFile = Join-Path $PSScriptRoot "setup-moderno.ps1"
$uninstallBatchFile = Join-Path $packageRoot "DESINSTALAR-Ambrosia-Nativo.bat"
$setupBatchFile = Join-Path $packageRoot "AMBROSIA-SETUP.bat"
$termsFile = Join-Path $packageRoot "TERMOS-DE-USO.txt"
$setupBannerFile = Join-Path $packageRoot "SetupBanner.png"
$iconFile = Join-Path $packageRoot "NativoSistemas.ico"
$brandFile = Join-Path $packageRoot "NativoSistemas.png"
$installRoot = Join-Path $env:LOCALAPPDATA "AmbrosiaNativo"
$exePath = Join-Path $installRoot "AmbrosiaNativo-v2.8.4.exe"
$legacyExePaths = @(
  (Join-Path $installRoot "AmbrosiaNativo.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v1.6.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v1.7.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v1.8.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v1.9.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.0.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.1.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.2.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.3.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.3.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.2.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.3.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.4.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.4.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.5.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.6.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.2.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.3.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.4.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.5.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.6.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.6.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.4.7.7.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.5.0.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.5.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.5.2.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.6.0.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.7.0.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.8.0.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.8.1.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.8.2.exe"),
  (Join-Path $installRoot "AmbrosiaNativo-v2.8.3.exe")
)
$installedSource = Join-Path $installRoot "AmbrosiaNativo.cs"
$installedLauncher = Join-Path $installRoot "iniciar-nativo.ps1"
$installedIcon = Join-Path $installRoot "NativoSistemas.ico"
$installedBrand = Join-Path $installRoot "NativoSistemas.png"
$installedScriptsRoot = Join-Path $installRoot "scripts"
$installedUninstaller = Join-Path $installedScriptsRoot "desinstalar-nativo.ps1"
$installedSetup = Join-Path $installedScriptsRoot "setup-moderno.ps1"
$installedUninstallBatch = Join-Path $installRoot "DESINSTALAR-Ambrosia-Nativo.bat"
$installedSetupBatch = Join-Path $installRoot "AMBROSIA-SETUP.bat"
$installedTerms = Join-Path $installRoot "TERMOS-DE-USO.txt"
$installedSetupBanner = Join-Path $installRoot "SetupBanner.png"
$dataFile = Join-Path $installRoot "dados.json"
$backupRoot = Join-Path $installRoot "backups"
$uninstallKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\AmbrosiaNativo"
New-Item -ItemType Directory -Path $installRoot -Force | Out-Null
New-Item -ItemType Directory -Path $installedScriptsRoot -Force | Out-Null

Write-Host "Configurando o acesso dos celulares na rede local..." -ForegroundColor Gray
$windowsAccount = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
& netsh http delete urlacl url=http://+:8787/ 2>$null | Out-Null
& netsh http add urlacl url=http://+:8787/ user="$windowsAccount" | Out-Null
& netsh advfirewall firewall delete rule name="Ambrosia Atendimento Mobile" 2>$null | Out-Null
& netsh advfirewall firewall add rule name="Ambrosia Atendimento Mobile" dir=in action=allow protocol=TCP localport=8787 profile=private | Out-Null

Write-Host "Fechando a versao anterior, se estiver aberta..." -ForegroundColor Gray
Get-Process -ErrorAction SilentlyContinue |
  Where-Object { $_.ProcessName -like "AmbrosiaNativo*" } |
  Stop-Process -Force -ErrorAction SilentlyContinue

# Quando o Windows bloqueia o EXE, o Ambrosia funciona hospedado pelo PowerShell.
# Encerra somente o PowerShell que abriu o launcher instalado do Ambrosia, sem
# interferir no processo deste instalador ou em outros scripts do usuario.
$installedLauncherPattern = "*" + $installedLauncher.Replace("\", "*") + "*"
Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
  Where-Object {
    ($_.Name -eq "powershell.exe" -or $_.Name -eq "pwsh.exe") -and
    $_.CommandLine -like $installedLauncherPattern -and
    $_.ProcessId -ne $PID
  } |
  ForEach-Object { Invoke-CimMethod -InputObject $_ -MethodName Terminate -ErrorAction SilentlyContinue | Out-Null }
Start-Sleep -Milliseconds 800

if (Test-Path -LiteralPath $dataFile -PathType Leaf) {
  New-Item -ItemType Directory -Path $backupRoot -Force | Out-Null
  $backupName = "antes-da-atualizacao-v2.8.4-" + (Get-Date -Format "yyyyMMdd-HHmmss") + "-dados.json"
  Copy-Item -LiteralPath $dataFile -Destination (Join-Path $backupRoot $backupName) -Force
  Write-Host "Backup dos dados atuais criado antes da atualizacao." -ForegroundColor Gray
}

function Remove-ExistingExecutable([string]$Path) {
  if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return }
  Unblock-File -LiteralPath $Path -ErrorAction SilentlyContinue
  for ($attempt = 1; $attempt -le 5; $attempt++) {
    try {
      Remove-Item -LiteralPath $Path -Force -ErrorAction Stop
      return
    }
    catch {
      if ($attempt -lt 5) { Start-Sleep -Milliseconds 500 }
    }
  }
  throw "O Ambrosia ainda esta aberto. Feche o aplicativo pelo Gerenciador de Tarefas e execute o instalador novamente."
}

Remove-ExistingExecutable $exePath

$source = Get-Content -LiteralPath $sourceFile -Raw -Encoding UTF8
if (-not (Test-Path -LiteralPath $iconFile -PathType Leaf)) { throw "O icone NativoSistemas.ico nao foi encontrado." }
if (-not (Test-Path -LiteralPath $brandFile -PathType Leaf)) { throw "A imagem NativoSistemas.png nao foi encontrada." }
if (-not (Test-Path -LiteralPath $uninstallerFile -PathType Leaf)) { throw "O desinstalador nao foi encontrado." }
if (-not (Test-Path -LiteralPath $setupFile -PathType Leaf)) { throw "O instalador moderno nao foi encontrado." }
if (-not (Test-Path -LiteralPath $uninstallBatchFile -PathType Leaf)) { throw "O atalho do desinstalador nao foi encontrado." }
if (-not (Test-Path -LiteralPath $setupBatchFile -PathType Leaf)) { throw "O atalho do Ambrosia Setup nao foi encontrado." }
if (-not (Test-Path -LiteralPath $termsFile -PathType Leaf)) { throw "Os Termos de Uso nao foram encontrados." }
if (-not (Test-Path -LiteralPath $setupBannerFile -PathType Leaf)) { throw "A imagem do instalador nao foi encontrada." }
Add-Type -AssemblyName Microsoft.CSharp
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$compiler = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler.GenerateExecutable = $true
$compiler.GenerateInMemory = $false
$compiler.OutputAssembly = $exePath
$compiler.CompilerOptions = "/target:winexe /win32icon:`"$iconFile`""
foreach ($assembly in @(
  "System.dll", "System.Core.dll", "System.Security.dll",
  "System.Runtime.Serialization.dll", "System.Xml.dll", "System.Drawing.dll",
  "System.Windows.Forms.dll", "System.Web.Extensions.dll"
)) { [void]$compiler.ReferencedAssemblies.Add($assembly) }
$result = $provider.CompileAssemblyFromSource($compiler, $source)
if ($result.Errors.HasErrors) {
  $messages = $result.Errors | ForEach-Object { $_.ToString() }
  throw ("Falha ao compilar o aplicativo:`r`n" + ($messages -join "`r`n"))
}

if (-not (Test-Path -LiteralPath $exePath -PathType Leaf)) {
  throw "O arquivo AmbrosiaNativo-v2.8.4.exe nao foi criado."
}

# A versao nova usa outro nome para nao depender da exclusao do EXE antigo.
# O arquivo antigo e removido somente quando o Windows liberar o acesso.
foreach ($legacyExePath in $legacyExePaths) {
  if (Test-Path -LiteralPath $legacyExePath -PathType Leaf) {
    Remove-Item -LiteralPath $legacyExePath -Force -ErrorAction SilentlyContinue
  }
}

Copy-Item -LiteralPath $sourceFile -Destination $installedSource -Force
Copy-Item -LiteralPath $launcherFile -Destination $installedLauncher -Force
Copy-Item -LiteralPath $iconFile -Destination $installedIcon -Force
Copy-Item -LiteralPath $brandFile -Destination $installedBrand -Force
Copy-Item -LiteralPath $uninstallerFile -Destination $installedUninstaller -Force
Copy-Item -LiteralPath $setupFile -Destination $installedSetup -Force
Copy-Item -LiteralPath $uninstallBatchFile -Destination $installedUninstallBatch -Force
Copy-Item -LiteralPath $setupBatchFile -Destination $installedSetupBatch -Force
Copy-Item -LiteralPath $termsFile -Destination $installedTerms -Force
Copy-Item -LiteralPath $setupBannerFile -Destination $installedSetupBanner -Force
Unblock-File -LiteralPath $exePath -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedSource -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedLauncher -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedIcon -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedBrand -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedUninstaller -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedSetup -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedUninstallBatch -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedSetupBatch -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedTerms -ErrorAction SilentlyContinue
Unblock-File -LiteralPath $installedSetupBanner -ErrorAction SilentlyContinue

$launchTarget = $exePath
$launchArguments = ""
$launchMode = "executavel"
try {
  $startedProcess = Start-Process -FilePath $exePath -PassThru -ErrorAction Stop
  Start-Sleep -Seconds 2
  if ($startedProcess.HasExited) { throw "O executavel fechou durante a inicializacao." }
}
catch {
  Write-Host ""
  Write-Host "O Windows bloqueou o EXE sem assinatura. Ativando modo compativel..." -ForegroundColor Yellow
  $launchTarget = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
  if (-not (Test-Path -LiteralPath $launchTarget -PathType Leaf)) {
    $launchTarget = (Get-Command powershell.exe -ErrorAction Stop).Source
  }
  $launchArguments = "-NoProfile -ExecutionPolicy Bypass -Sta -WindowStyle Hidden -File `"$installedLauncher`""
  $launchMode = "compativel"
  $compatibleProcess = Start-Process -FilePath $launchTarget -ArgumentList $launchArguments -PassThru -WindowStyle Hidden -ErrorAction Stop
  Start-Sleep -Seconds 3
  if ($compatibleProcess.HasExited) {
    throw "O modo compativel tambem nao permaneceu aberto. Execute novamente o instalador e envie a mensagem exibida."
  }
}

$shell = New-Object -ComObject WScript.Shell
$desktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "Ambrosia Nativo.lnk"
$menuFolder = Join-Path ([Environment]::GetFolderPath("Programs")) "Ambrosia"
$menuShortcut = Join-Path $menuFolder "Ambrosia Nativo.lnk"
$menuUninstallShortcut = Join-Path $menuFolder "Desinstalar Ambrosia Nativo.lnk"
New-Item -ItemType Directory -Path $menuFolder -Force | Out-Null

foreach ($shortcutPath in @($desktopShortcut, $menuShortcut)) {
  $shortcut = $shell.CreateShortcut($shortcutPath)
  $shortcut.TargetPath = $launchTarget
  $shortcut.Arguments = $launchArguments
  $shortcut.WorkingDirectory = $installRoot
  $shortcut.Description = "Sistema nativo da Ambrosia - sem navegador"
  $shortcut.IconLocation = "$exePath,0"
  if ($launchMode -eq "compativel") { $shortcut.WindowStyle = 7 }
  $shortcut.Save()
}

$uninstallShortcut = $shell.CreateShortcut($menuUninstallShortcut)
$uninstallShortcut.TargetPath = $installedUninstallBatch
$uninstallShortcut.WorkingDirectory = $installRoot
$uninstallShortcut.Description = "Desinstalar o Ambrosia Nativo"
$uninstallShortcut.IconLocation = "$exePath,0"
$uninstallShortcut.Save()

# Faz o Ambrosia aparecer em Configuracoes > Aplicativos instalados do Windows.
$powerShellPath = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
$uninstallCommand = "`"$powerShellPath`" -NoProfile -ExecutionPolicy Bypass -Sta -File `"$installedSetup`" -Acao Desinstalar"
New-Item -Path $uninstallKey -Force | Out-Null
Set-ItemProperty -Path $uninstallKey -Name "DisplayName" -Value "Ambrosia Nativo"
Set-ItemProperty -Path $uninstallKey -Name "DisplayVersion" -Value "2.8.4"
Set-ItemProperty -Path $uninstallKey -Name "Publisher" -Value "Nativo Sistemas"
Set-ItemProperty -Path $uninstallKey -Name "DisplayIcon" -Value "$exePath,0"
Set-ItemProperty -Path $uninstallKey -Name "InstallLocation" -Value $installRoot
Set-ItemProperty -Path $uninstallKey -Name "UninstallString" -Value $uninstallCommand
Set-ItemProperty -Path $uninstallKey -Name "NoModify" -Value 1 -Type DWord
Set-ItemProperty -Path $uninstallKey -Name "NoRepair" -Value 1 -Type DWord

Write-Host ""
Write-Host "Instalacao concluida." -ForegroundColor Green
Write-Host "Programa criado: $exePath" -ForegroundColor White
Write-Host "Atalho Ambrosia Nativo criado na Area de Trabalho." -ForegroundColor White
Write-Host "Desinstalador registrado na lista de aplicativos do Windows." -ForegroundColor White
Write-Host "Aplicativo celular liberado na rede privada pela porta 8787." -ForegroundColor White
if ($launchMode -eq "compativel") {
  Write-Host "Modo compativel ativado porque o Controle de Aplicativo bloqueou o EXE." -ForegroundColor Yellow
  Write-Host "O sistema continua nativo e nao usa navegador." -ForegroundColor White
}
