@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "CERT_FILE=%~dp0ab-dev-root-ca.cer"
set "TEMP_CERT=%TEMP%\ab-dev-root-ca.cer"

if exist "%CERT_FILE%" goto :install

echo American Bakeshop root certificate was not found next to this installer.
echo Attempting to download it from the intranet over HTTP...
echo.

set "CERT_FILE=%TEMP_CERT%"
for %%U in (
  "http://ab.home.arpa/certs/ab-dev-root-ca.cer"
  "http://admin.ab.home.arpa/certs/ab-dev-root-ca.cer"
  "http://americanbakeshop.home.arpa/certs/ab-dev-root-ca.cer"
) do (
  if not exist "%CERT_FILE%" (
    echo Trying %%~U
    powershell -NoProfile -ExecutionPolicy Bypass -Command "try { Invoke-WebRequest -Uri '%%~U' -OutFile '%TEMP_CERT%' -UseBasicParsing; exit 0 } catch { exit 1 }" >nul 2>nul
  )
)

if not exist "%CERT_FILE%" (
  echo.
  echo ERROR: Could not download ab-dev-root-ca.cer.
  echo Download the certificate from /cert-setup and place it in the same folder as this installer, then run again.
  echo.
  pause
  exit /b 1
)

:install
echo Installing American Bakeshop intranet root certificate:
echo "%CERT_FILE%"
echo.

net session >nul 2>nul
if %ERRORLEVEL% EQU 0 (
    echo Administrator detected. Installing for the whole computer...
    certutil -addstore -f Root "%CERT_FILE%"
) else (
    echo Administrator permission was not detected.
    echo Installing for the current Windows user only...
    certutil -user -addstore -f Root "%CERT_FILE%"
)

if %ERRORLEVEL% NEQ 0 (
    echo.
    echo ERROR: Certificate install failed.
    echo Try right-clicking this file and choosing Run as administrator.
    echo.
    pause
    exit /b 1
)

echo.
echo Done.
echo Close all Chrome/Edge windows and reopen:
echo https://admin.ab.home.arpa
echo.
pause
