param(
    [string]$OutputPath = ""
)

$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$root = Join-Path $root '..'
$buildDir = Join-Path $root 'build/deploy'
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
    $outputFile = Join-Path $root 'build/elixforms-webservices-deploy.zip'
}
else {
    $outputFile = $OutputPath
}

$useDockerComposer = $false
$dockerRoot = $null

New-Item -ItemType Directory -Force -Path $buildDir | Out-Null
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $outputFile) | Out-Null

if (Test-Path $buildDir) {
    Get-ChildItem -Path $buildDir -Force | Remove-Item -Recurse -Force
}

if (Test-Path $outputFile) {
    Remove-Item $outputFile -Force
}

if (-not (Get-Command composer -ErrorAction SilentlyContinue)) {
    Write-Host "Composer non trovato localmente. Verifico se Docker è disponibile..."
    if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
        throw "Composer non trovato e Docker mancante! Installa Composer o Docker prima di generare il pacchetto."
    }

    $dockerRoot = $root -replace '\\', '/'
    if ($dockerRoot -match '^([A-Za-z]):') {
        $dockerRoot = "/$($Matches[1].ToLower())$($dockerRoot.Substring(2))"
    }

    Write-Host "Docker trovato. Root: '$dockerRoot' Test di Composer tramite container..."
    docker run --rm -v "$($dockerRoot):/app" -w /app composer:2 composer --version 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "Docker presente, ma Composer non riesce ad avviarsi tramite container. Installa Composer localmente o verifica Docker."
    }

    $useDockerComposer = $true
}

Push-Location $root
try {
    Write-Host "[1/4] Installazione dipendenze PHP"
    if ($useDockerComposer) {
        docker run --rm -v "$($dockerRoot):/app" -w /app composer:2 composer install --no-dev --optimize-autoloader
    }
    else {
        composer install --no-dev --optimize-autoloader
    }

    Write-Host "[2/4] Preparazione contenuti per il deploy"
    Copy-Item -Path (Join-Path $root 'public') -Destination (Join-Path $buildDir 'public') -Recurse -Force
    Copy-Item -Path (Join-Path $root 'src') -Destination (Join-Path $buildDir 'src') -Recurse -Force
    Copy-Item -Path (Join-Path $root 'config') -Destination (Join-Path $buildDir 'config') -Recurse -Force
    Copy-Item -Path (Join-Path $root 'bootstrap.php') -Destination (Join-Path $buildDir 'bootstrap.php') -Force
    Copy-Item -Path (Join-Path $root 'composer.json') -Destination (Join-Path $buildDir 'composer.json') -Force

    if (Test-Path (Join-Path $root 'composer.lock')) {
        Copy-Item -Path (Join-Path $root 'composer.lock') -Destination (Join-Path $buildDir 'composer.lock') -Force
    }

    if (Test-Path (Join-Path $root 'vendor')) {
        Copy-Item -Path (Join-Path $root 'vendor') -Destination (Join-Path $buildDir 'vendor') -Recurse -Force
    }

    @'
Deploy Apache PHP
=================
1. Estrai il contenuto di questo archivio nella cartella del sito web del server.
2. Imposta il DocumentRoot su: C:\percorso\destinazione\public
3. Assicurati che il server web abbia permessi di lettura per la cartella e scrittura per eventuali directory di storage.
'@ | Set-Content -Path (Join-Path $buildDir 'README.txt') -Encoding UTF8

    Write-Host "[3/4] Creazione archivio"
    if (Get-Command Compress-Archive -ErrorAction SilentlyContinue) {
        Compress-Archive -Path (Join-Path $buildDir '*') -DestinationPath $outputFile -Force
    }
    else {
        throw "Compress-Archive non disponibile. Usa Windows PowerShell 5+ o PowerShell 7."
    }

    $outputFile = Resolve-Path -LiteralPath $outputFile

    Write-Host "[4/4] Archivio pronto"
    Write-Host "Percorso: '$outputFile'"
    Write-Host ""
    Write-Host "================================================================================"
    Write-Host ""
    Write-Host "Per usare il pacchetto (Windows):"
    Write-Host "  Expand-Archive -Path $outputFile -DestinationPath C:\percorso\destinazione"
    Write-Host "  poi imposta Apache DocumentRoot a C:\percorso\destinazione\public"
    Write-Host ""
    Write-Host "--------------------------------------------------------------------------------"
    Write-Host ""
    Write-Host "Per usare il pacchetto (Linux, senza PowerShell):"
    Write-Host "  unzip $outputFile -d /percorso/destinazione"
    Write-Host "  poi imposta Apache DocumentRoot a /percorso/destinazione/public"
    Write-Host "  assicurati che l'utente del server web abbia permessi di lettura/esecuzione e scrittura sulle directory necessarie, ad esempio:"
    Write-Host "    sudo chown -R www-data:www-data /percorso/destinazione"
    Write-Host "    sudo find /percorso/destinazione -type d -exec chmod 755 {} \;"
    Write-Host "    sudo find /percorso/destinazione -type f -exec chmod 644 {} \;"
}
finally {
    Pop-Location
}