@echo off
REM ===================================================================
REM  Starhigh laptop setup
REM
REM  Right-click this file and choose "Run as administrator" (double-click
REM  works too; Windows asks the same question). Nothing to type. It enrols
REM  the machine with the portal, installs the standard software, creates the
REM  staff member's Windows account and registers the agent so approved
REM  software installs without an admin password ever again.
REM
REM  It downloads the latest setup scripts from the portal. The copies beside
REM  this file (on the USB kit) are used only when there is no internet yet.
REM
REM  Also available at https://setup.starhighgroup.com
REM ===================================================================

setlocal
title Starhigh Group - Workstation Setup

set "PORTAL=https://portal.starhighgroup.com"
REM Paths travel to PowerShell as environment variables, never spliced into a
REM quoted PowerShell literal: a folder with an apostrophe (C:\Users\O'Neil)
REM or a percent sign would otherwise end the string early and fail silently.
set "SELF=%~f0"
set "HERE=%~dp0"

REM No secret here by design. The wizard signs the admin in with a one-time
REM emailed code, and the token that returns is what authorises enrolment.

REM --- Re-launch elevated if we are not already administrator. This is
REM --- the single UAC prompt for the whole process.
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo Starting Starhigh Workstation Setup...
    powershell -NoProfile -Command "Start-Process -FilePath $env:SELF -Verb RunAs"
    if %errorLevel% neq 0 (
        echo.
        echo  Setup needs administrator approval. Run it again and
        echo  click Yes when Windows asks for permission.
        echo.
        pause
    )
    exit /b
)

cd /d "%HERE%"
set "WORKDIR=%TEMP%\starhigh-setup"
set "STAGE=%TEMP%\starhigh-setup-new"

REM --- Always try the portal first, so a USB stick prepared months ago still
REM --- runs today's scripts. Everything lands in a staging folder and is
REM --- checked before it replaces the previous set: all four files present,
REM --- each starting with a PowerShell comment block (a Wi-Fi sign-in page
REM --- would not) and each read to its end (a dropped connection leaves a
REM --- truncated file that would fail halfway through setup).
echo  Downloading setup scripts...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "[Net.ServicePointManager]::SecurityProtocol=3072;" ^
  "$stage=$env:STAGE; $work=$env:WORKDIR; $portal=$env:PORTAL;" ^
  "Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue;" ^
  "New-Item -ItemType Directory -Path $stage -Force | Out-Null;" ^
  "try {" ^
  "  foreach ($f in 'install-agent.ps1','starhigh-agent.ps1','Setup-Wizard.ps1','starhigh-notify.ps1') {" ^
  "    $dst = Join-Path $stage $f;" ^
  "    Invoke-WebRequest ($portal + '/agent/' + $f) -OutFile $dst -UseBasicParsing;" ^
  "    $head = (Get-Content $dst -TotalCount 1 -ErrorAction Stop) -join '';" ^
  "    if ($head -notmatch '^\s*<#') { throw ($f + ' did not download correctly. If this Wi-Fi needs a browser sign-in, do that first, then run this again.') }" ^
  "    if ((Get-Item $dst).Length -lt 2000) { throw ($f + ' was cut short during download. Check the connection and run this again.') }" ^
  "  }" ^
  "  New-Item -ItemType Directory -Path $work -Force | Out-Null;" ^
  "  Copy-Item (Join-Path $stage '*') $work -Force;" ^
  "  exit 0" ^
  "} catch { Write-Host ''; Write-Host ('  ' + $_.Exception.Message) -ForegroundColor Red; exit 1 }"
if %errorLevel% neq 0 (
    if exist "%HERE%Setup-Wizard.ps1" if exist "%HERE%install-agent.ps1" if exist "%HERE%starhigh-agent.ps1" (
        echo  No internet yet - using the copies on this drive.
        set "WORKDIR=%HERE%"
        goto :run
    )
    goto :failed
)

:run
REM --- Files arriving from a USB drive or the internet carry a
REM --- mark-of-the-web that blocks execution; clear it.
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "Get-ChildItem (Join-Path $env:WORKDIR '*.ps1') | Unblock-File -ErrorAction SilentlyContinue"

REM The wizard hides this console itself once it starts, and reports any
REM startup failure in a dialog -- so there is no silent-failure risk in
REM launching it minimised.
start "" /min powershell -NoProfile -ExecutionPolicy Bypass -File "%WORKDIR%\Setup-Wizard.ps1" -PortalUrl "%PORTAL%" -ScriptDir "%WORKDIR%"
exit /b 0

:failed
echo.
echo  ------------------------------------------------
echo   SETUP DID NOT COMPLETE
echo.
echo   Check the laptop has internet access and that its
echo   date and time are correct, then run this again.
echo   If it keeps failing, send a photo of this window
echo   to IT.
echo  ------------------------------------------------
echo.
pause
exit /b 1
