@echo off
setlocal EnableExtensions
title Be Secure IT - Nieuwe PC

set "BSI_TMP=%ProgramData%\Be Secure IT\Bootstrap"
set "BSI_PS=%BSI_TMP%\BSecureIT-NewPC-Provision.ps1"
set "BSI_SHA=%BSI_PS%.sha256"
set "BSI_URL=https://repo.bsecurit.be/install/BSecureIT-NewPC-Provision.ps1"
set "BSI_HASH_URL=%BSI_URL%.sha256"
set "BSI_ERROR=%ProgramData%\Be Secure IT\Provisioning\LAST-ERROR.txt"

if not exist "%BSI_TMP%" mkdir "%BSI_TMP%" >nul 2>&1

echo ============================================================
echo  BE SECURE IT - NIEUWE PC
echo ============================================================
echo.
echo Installer downloaden en SHA256 controleren...
echo.

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;" ^
  "$u=$env:BSI_URL + '?nocache=' + [DateTimeOffset]::UtcNow.ToUnixTimeSeconds();" ^
  "$h=$env:BSI_HASH_URL + '?nocache=' + [DateTimeOffset]::UtcNow.ToUnixTimeSeconds();" ^
  "Invoke-WebRequest -UseBasicParsing -Uri $u -OutFile $env:BSI_PS;" ^
  "Invoke-WebRequest -UseBasicParsing -Uri $h -OutFile $env:BSI_SHA;" ^
  "$expected=((Get-Content $env:BSI_SHA -Raw).Trim() -split '\s+')[0].ToUpperInvariant();" ^
  "$actual=(Get-FileHash $env:BSI_PS -Algorithm SHA256).Hash.ToUpperInvariant();" ^
  "if($expected -notmatch '^[A-F0-9]{64}$'){throw 'Ongeldige SHA256 metadata'};" ^
  "if($actual -ne $expected){throw 'Be Secure IT installer hashvalidatie mislukt'};" ^
  "Unblock-File $env:BSI_PS -ErrorAction SilentlyContinue;" ^
  "Write-Host ('SHA256 OK: ' + $actual) -ForegroundColor Green"

if errorlevel 1 (
  echo.
  echo ============================================================
  echo  DOWNLOAD / HASHVALIDATIE MISLUKT
  echo ============================================================
  echo.
  pause
  exit /b 1
)

net session >nul 2>&1
if %errorlevel%==0 (
  powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%BSI_PS%"
  set "RC=%ERRORLEVEL%"
) else (
  powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
    "$p=Start-Process powershell.exe -Verb RunAs -Wait -PassThru -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-File','\"%BSI_PS%\"'); exit $p.ExitCode"
  set "RC=%ERRORLEVEL%"
)

if not "%RC%"=="0" (
  echo.
  echo ============================================================
  echo  BSI NEW PC PROVISIONING FAILED - EXITCODE %RC%
  echo ============================================================
  echo.
  if exist "%BSI_ERROR%" (
    echo Laatste fout:
    echo ------------------------------------------------------------
    type "%BSI_ERROR%"
    echo ------------------------------------------------------------
  ) else (
    echo Geen LAST-ERROR.txt gevonden.
    echo Controleer:
    echo   C:\ProgramData\Be Secure IT\Provisioning\Logs
  )
  echo.
  echo Dit venster blijft open zodat de fout gelezen kan worden.
  pause
  exit /b %RC%
)

echo.
echo BSI_NEW_PC_LAUNCHER_PASS
exit /b 0
