param(
   [string]$TargetDir,
   [string]$ExportUrl
)

$ErrorActionPreference = 'Stop'

if ([string]::IsNullOrWhiteSpace($TargetDir) -or [string]::IsNullOrWhiteSpace($ExportUrl)) {
   Write-Host "Uso: sync_vitruvio_zip.ps1 <pasta_destino> <url_webservice>"
   exit 1
}

$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("vitruvio-sync-" + [System.Guid]::NewGuid().ToString('N'))
$zipFile = Join-Path $tempDir 'vitruvio_completo.zip'
$extractDir = Join-Path $tempDir 'extract'
$pastasExportacao = @('Paineis', 'Libs', 'WebServices', 'Processos', 'Relatorios')

function Cleanup {
   if (Test-Path -LiteralPath $tempDir) {
      Remove-Item -LiteralPath $tempDir -Recurse -Force
   }
}

try {
   New-Item -ItemType Directory -Path $extractDir -Force | Out-Null
   New-Item -ItemType Directory -Path $TargetDir -Force | Out-Null

   Write-Host 'Baixando ZIP do webservice...'
   Invoke-WebRequest -Uri $ExportUrl -OutFile $zipFile

   Write-Host 'Extraindo ZIP...'
   Expand-Archive -LiteralPath $zipFile -DestinationPath $extractDir -Force

   foreach ($pasta in $pastasExportacao) {
      $sourceDir = Join-Path $extractDir $pasta

      if (-not (Test-Path -LiteralPath $sourceDir -PathType Container)) {
         throw "Erro: pasta obrigatoria nao encontrada no ZIP: $pasta"
      }
   }

   Write-Host "Sincronizando conteudo em $TargetDir..."

   foreach ($pasta in $pastasExportacao) {
      $sourceDir = Join-Path $extractDir $pasta
      $destinationDir = Join-Path $TargetDir $pasta

      if (Test-Path -LiteralPath $destinationDir) {
         Remove-Item -LiteralPath $destinationDir -Recurse -Force
      }

      Copy-Item -LiteralPath $sourceDir -Destination $TargetDir -Recurse -Force
   }

   Write-Host 'Sincronizacao concluida com sucesso.'
}
catch {
   Write-Error $_.Exception.Message
   exit 1
}
finally {
   Cleanup
}