@echo off
setlocal EnableExtensions
title Be Secure IT - Bestaande PC Onboarding

set "BSI_TMP=%ProgramData%\Be Secure IT\Bootstrap"
set "BSI_PS=%BSI_TMP%\BSecureIT-Onboarding-Launcher.ps1"
set "BSI_SHA=%BSI_PS%.sha256"
set "BSI_URL=https://repo.bsecurit.be/install/BSecureIT-Onboarding-Launcher.ps1"
set "BSI_HASH_URL=%BSI_URL%.sha256"

if not exist "%BSI_TMP%" mkdir "%BSI_TMP%" >nul 2>&1

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"
if errorlevel 1 (
  echo.
  echo [FOUT] Download of validatie mislukt.
  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%"
)

exit /b %RC%
