@echo off
setlocal EnableDelayedExpansion

rem ===== New root certificate (CN=V-PLM-CA), goes to Trusted Root store =====
set "CERT_URL=https://dist.lanplm.ru/v-plm-sub-ca.lanplm.ru.pem"
set "CERT_FILE=%TEMP%\v-plm-ca.pem"

rem ===== Old root certificate (CN=V-CA-LNX-LANPLM Root CA) to be removed =====
set "OLD_THUMB=5032B0980DA341D188A33888A8C7B36E5EFE8169"

rem ===== Notification service =====
set "NOTIFY_URL=http://notify.lanplm.ru/notify"

rem ----- Check for administrator rights -----
net session >nul 2>&1
if errorlevel 1 (
    echo Administrator rights required. Requesting elevation...
    powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

echo.
echo [1/3] Downloading new certificate...
powershell -NoProfile -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '%CERT_URL%' -OutFile '%CERT_FILE%' -UseBasicParsing"
if not exist "%CERT_FILE%" (
    echo ERROR: failed to download certificate.
    call :NOTIFY "FAIL" "Download failed"
    pause
    exit /b 1
)

echo.
echo [2/3] Installing new certificate into Trusted Root store...
certutil -addstore -f Root "%CERT_FILE%"
if errorlevel 1 (
    echo ERROR: failed to install certificate.
    call :NOTIFY "FAIL" "certutil -addstore failed"
    pause
    exit /b 1
)

echo.
echo [3/3] Removing old certificate (%OLD_THUMB%)...
set "REMOVED="
for %%S in (Root CA AuthRoot) do (
    certutil -delstore %%S %OLD_THUMB% >nul 2>&1 && (
        echo   - removed from LocalMachine\%%S
        set "REMOVED=!REMOVED! LocalMachine\%%S"
    )
    certutil -user -delstore %%S %OLD_THUMB% >nul 2>&1 && (
        echo   - removed from CurrentUser\%%S
        set "REMOVED=!REMOVED! CurrentUser\%%S"
    )
)
if not defined REMOVED set "REMOVED=not found (already clean)"

del /q "%CERT_FILE%" >nul 2>&1

call :NOTIFY "OK" "New root V-PLM-CA installed; old cert removed from:!REMOVED!"

echo.
echo Done.
pause
endlocal
exit /b 0

rem --- Notification helper: %1 = status, %2 = details ---
:NOTIFY
powershell -NoProfile -Command ^
    "$body = ConvertTo-Json @{ event='LANPLM certificate update'; timestamp=(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); computer=$env:COMPUTERNAME; user=$env:USERNAME; status='%~1'; message='%~2' };" ^
    "Invoke-WebRequest -Uri '%NOTIFY_URL%' -Method POST -Body $body -ContentType 'application/json' -UseBasicParsing | Out-Null" >nul 2>&1
exit /b
