param([Alias('EnrollmentKey')][string]$EnrollmentCode = '', [switch]$RepairOnly)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
function Get-RBFileSha256([string]$Path) {
    $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
    $sha = [Security.Cryptography.SHA256]::Create()
    try { return ([BitConverter]::ToString($sha.ComputeHash($stream))).Replace('-', '') }
    finally { $sha.Dispose(); $stream.Dispose() }
}
$source = Join-Path $PSScriptRoot 'App'
$manifestPath = Join-Path $PSScriptRoot 'manifest.json'
if (Test-Path -LiteralPath $manifestPath) {
    $integrityIssues = New-Object Collections.Generic.List[string]
    $manifestEntries = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
    foreach ($entry in $manifestEntries) {
        $candidate = Join-Path $PSScriptRoot ([string]$entry.path)
        if (-not (Test-Path -LiteralPath $candidate)) {
            $integrityIssues.Add("File mancante: $($entry.path)")
            continue
        }
        try {
            if ((Get-RBFileSha256 -Path $candidate) -ne $entry.sha256) {
                $integrityIssues.Add("File modificato: $($entry.path)")
            }
        } catch {
            $integrityIssues.Add("File non leggibile: $($entry.path) - $($_.Exception.Message)")
        }
    }
    if ($integrityIssues.Count -gt 0) {
        $detail = ($integrityIssues | Select-Object -First 5) -join "`n"
        $message = "Il pacchetto non puo essere installato.`n`n$detail`n`nEstrai nuovamente lo ZIP in una cartella vuota. Se manca restic.exe, controlla la cronologia di Protezione di Windows."
        [Windows.Forms.MessageBox]::Show($message, 'RansomBackup FREE', 'OK', 'Error') | Out-Null
        exit 1
    }
}
$deploymentPath = Join-Path $source 'deployment.json'
if (Test-Path -LiteralPath $deploymentPath) {
    $deployment = Get-Content -LiteralPath $deploymentPath -Raw | ConvertFrom-Json
    if ($deployment.require_signed) {
        foreach ($scriptFile in Get-ChildItem -LiteralPath $source -Filter '*.ps1' -File) {
            if ((Get-AuthenticodeSignature -LiteralPath $scriptFile.FullName).Status -ne 'Valid') {
                [Windows.Forms.MessageBox]::Show('La firma digitale del pacchetto non è valida.', 'RansomBackup FREE', 'OK', 'Error') | Out-Null
                exit 1
            }
        }
    }
}
$destination = Join-Path $env:LOCALAPPDATA 'Programs\RansomBackupFREE'
if (-not (Test-Path (Join-Path $source 'restic.exe'))) {
    [Windows.Forms.MessageBox]::Show('Pacchetto incompleto: restic.exe non trovato.', 'RansomBackup FREE', 'OK', 'Error') | Out-Null
    exit 1
}
New-Item -ItemType Directory -Force -Path $destination | Out-Null
Copy-Item -Path (Join-Path $source '*') -Destination $destination -Recurse -Force
$utf8Bom = New-Object Text.UTF8Encoding($true)
Get-ChildItem -LiteralPath $destination -Filter '*.ps1' -File | ForEach-Object {
    $content = [IO.File]::ReadAllText($_.FullName, [Text.Encoding]::UTF8)
    [IO.File]::WriteAllText($_.FullName, $content, $utf8Bom)
}
. (Join-Path $destination 'Common.ps1')
$iconPath = New-RBAppIcon

$startMenu = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\RansomBackup FREE'
New-Item -ItemType Directory -Force -Path $startMenu | Out-Null
$oldStatusShortcut = Join-Path $startMenu 'Stato RansomBackup FREE.lnk'
if (Test-Path -LiteralPath $oldStatusShortcut) { Remove-Item -LiteralPath $oldStatusShortcut -Force }
$shell = New-Object -ComObject WScript.Shell
function New-RBStartShortcut([string]$FileName,[string]$ScriptName) {
    $item = $shell.CreateShortcut((Join-Path $startMenu $FileName))
    $item.TargetPath = (Join-Path $env:WINDIR 'System32\wscript.exe')
    $item.Arguments = "`"$(Join-Path $destination 'LaunchHidden.vbs')`" `"$ScriptName`""
    $item.WorkingDirectory = $destination
    if ($iconPath -and (Test-Path -LiteralPath $iconPath)) { $item.IconLocation = "$iconPath,0" }
    $item.Save()
}
New-RBStartShortcut 'RansomBackup FREE.lnk' 'Dashboard.ps1'
New-RBStartShortcut 'Area personale RansomBackup FREE.lnk' 'Status.ps1'
New-RBStartShortcut 'Gestisci cartelle RansomBackup FREE.lnk' 'ManageFolders.ps1'
New-RBStartShortcut 'Stampa chiave RansomBackup FREE.lnk' 'RecoveryKey.ps1'
New-RBStartShortcut 'Ripristina file RansomBackup FREE.lnk' 'Restore.ps1'
New-RBStartShortcut 'Ricomincia con un nuovo account.lnk' 'ResetAccount.ps1'
New-RBStartShortcut 'Disinstalla RansomBackup FREE.lnk' 'Uninstall.ps1'

if ($RepairOnly) {
    [void](Register-RBScheduledTask)
    exit 0
}

$wizardParameters = @{ Gateway = 'https://free.ransombackup.com' }
if (-not [string]::IsNullOrWhiteSpace($EnrollmentCode)) {
    $wizardParameters.EnrollmentCode = $EnrollmentCode
}
& (Join-Path $destination 'SetupWizard.ps1') @wizardParameters
$wizardExit = $LASTEXITCODE
if ($wizardExit -eq 0 -and (Test-Path -LiteralPath (Join-Path $env:APPDATA 'RansomBackupFREE\config.json'))) {
    Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $destination 'LaunchHidden.vbs')`"",'Dashboard.ps1')
}
exit $wizardExit
