@echo off
rem paliad-companion-update.cmd - replaces this folder's contents with the build
rem companion.paliad.de publishes. It leaves Chrome's entry alone, so the pairing with paliad
rem survives the update: the token lives in this extension's own profile in the browser, and
rem removing the entry is what loses it. Only an administrator can hand out a new one.
rem
rem It lives inside the extension folder and updates its siblings, so there is nothing to
rem configure and nothing to type. It refuses any folder that does not hold this extension's
rem manifest.json, and it writes nowhere but this folder and its own directory under %TEMP%.
rem
rem Plain batch, so no PowerShell execution policy applies. curl.exe, certutil.exe and tar.exe all
rem ship with Windows 10 and 11. The --ssl-revoke-best-effort below needs curl 7.70 or newer, so it
rem is probed for and not passed blind.
rem
rem Contract with extension/deploy/Dockerfile: latest.json carries version, version_name, zip and
rem sha256, one field per line with two-space indentation, which is also how manifest.json is
rem written. One line reader below reads either. Every comparison is on `version`, which is
rem Chrome's own and the only one that is ordered; `version_name` is only ever printed.
rem extension/tests/companion-updater_test.sh pins both sides.
rem
rem IT IS A COPY of youpcms's extension/deploy/update/yoUPC-companion-update.cmd, the way
rem deploy/release-crx.sh and deploy/zip-dist.ts are copies, and for the same reason. What differs:
rem the site, the archive's name, its own name, the %TEMP% directory (a Windows machine can hold
rem both companions, and one work directory for two scripts would collide), the folder marker, and
rem youpcms's rename of a pre-release copy of itself, which paliad has never published and so
rem carries nothing to rename. The marker is the one difference that matters: both manifests target
rem cms.unifiedpatentcourt.org, so only paliad.de tells the two folders apart, and without it this
rem script would empty the yoUPCms folder and install paliad into it.

setlocal EnableExtensions

set "SITE=https://companion.paliad.de"
set "WORK=%TEMP%\paliad-companion-update"
set "TARGET=%~dp0"
if "%TARGET:~-1%"=="\" set "TARGET=%TARGET:~0,-1%"

echo.
echo Paliad companion updater
echo   folder: %TARGET%
echo.

where /q curl.exe || goto :no_tool
where /q certutil.exe || goto :no_tool
where /q tar.exe || goto :no_tool

rem Both reads below carry %CURL_TLS%. On a network that blocks the revocation responders, schannel
rem fails the handshake with CRYPT_E_NO_REVOCATION_CHECK (0x80092012) instead of proceeding;
rem --ssl-revoke-best-effort keeps the check wherever a responder answers and skips it only where it
rem cannot be reached. Not --ssl-no-revoke, which drops the check even where it would run. What makes
rem best-effort acceptable is that the certificate is not the integrity guard here: the sha256
rem comparison against latest.json is, and nothing about the transport can weaken it.
rem
rem The option arrived in curl 7.70.0 and Windows 10 1803 shipped curl.exe 7.55.1, which ends the run
rem with exit 2 on an option it does not know, before any request. Since the installed copy of this
rem script is what runs, passing it unconditionally would leave such a machine unable to update at
rem all. So it is passed only where this curl.exe lists it in its own help.
set "CURL_TLS="
curl.exe --help all 2>nul | findstr /c:ssl-revoke-best-effort >nul && set "CURL_TLS=--ssl-revoke-best-effort"

rem The folder this script sits in must be the extension's own, or it stops here. Two markers in
rem one manifest.json: paliad.de is what the yoUPCms companion's manifest does not carry, and a
rem check anchored on the display name would break on the next rebrand.
if "%TARGET:~-1%"==":" goto :not_extension
if not exist "%TARGET%\manifest.json" goto :not_extension
findstr /c:manifest_version "%TARGET%\manifest.json" >nul || goto :not_extension
findstr /c:paliad.de "%TARGET%\manifest.json" >nul || goto :not_extension

call :read_field "%TARGET%\manifest.json" version
set "HAVE_VER=%FIELD%"
call :read_field "%TARGET%\manifest.json" version_name
set "HAVE_NAME=%FIELD%"
set "SHOW_HAVE=%HAVE_VER%"
if defined HAVE_NAME set "SHOW_HAVE=%HAVE_NAME%"
if defined HAVE_VER echo   installed: %SHOW_HAVE%

rd /s /q "%WORK%" >nul 2>&1
mkdir "%WORK%" || goto :no_temp

echo   reading %SITE%/latest.json
curl.exe -fsS %CURL_TLS% --connect-timeout 10 --max-time 30 -o "%WORK%\latest.json" "%SITE%/latest.json" || goto :no_site

call :read_field "%WORK%\latest.json" version
set "NEW_VER=%FIELD%"
call :read_field "%WORK%\latest.json" zip
set "NEW_ZIP=%FIELD%"
call :read_field "%WORK%\latest.json" sha256
set "NEW_SHA=%FIELD%"
rem Printed and never compared, so a latest.json written before this field existed costs nothing:
rem the numeric version stands in wherever it is missing.
call :read_field "%WORK%\latest.json" version_name
set "NEW_NAME=%FIELD%"

rem Every one of the three is checked against the shape it must have. The zip's name becomes a URL
rem and a file name, so it is pinned to a bare name in the site root and can carry no path.
if not defined NEW_VER goto :bad_latest
if not defined NEW_ZIP goto :bad_latest
if not defined NEW_SHA goto :bad_latest
echo %NEW_VER%|findstr /r "^[0-9][0-9.]*$" >nul || goto :bad_latest
echo %NEW_ZIP%|findstr /r "^paliad-companion-v[0-9][0-9.]*\.zip$" >nul || goto :bad_latest
echo %NEW_SHA%|findstr /r "^[0-9a-fA-F][0-9a-fA-F]*$" >nul || goto :bad_latest

set "SHOW_NEW=%NEW_VER%"
if defined NEW_NAME set "SHOW_NEW=%NEW_NAME%"
echo   published: %SHOW_NEW%
if /i "%NEW_VER%"=="%HAVE_VER%" goto :already_current

echo   downloading %NEW_ZIP%
curl.exe -fsS %CURL_TLS% --connect-timeout 10 --max-time 600 -o "%WORK%\%NEW_ZIP%" "%SITE%/%NEW_ZIP%" || goto :no_zip
set "ZIP_BYTES="
for %%F in ("%WORK%\%NEW_ZIP%") do set "ZIP_BYTES=%%~zF"
if not defined ZIP_BYTES goto :no_zip
rem The build is about a megabyte, so this floor is five times under it and only ever catches a
rem download that stopped early. A wrong URL is already curl -f's refusal.
if %ZIP_BYTES% LSS 200000 goto :zip_too_small

rem certutil writes the hash on its second line, as one run of hex on Windows 10 and 11 and as
rem space-separated byte pairs on older releases; stripping the spaces reads either.
set "ACTUAL="
for /f "skip=1 delims=" %%H in ('certutil -hashfile "%WORK%\%NEW_ZIP%" SHA256') do if not defined ACTUAL set "ACTUAL=%%H"
if not defined ACTUAL goto :no_hash
set "ACTUAL=%ACTUAL: =%"
if /i not "%ACTUAL%"=="%NEW_SHA%" goto :bad_checksum
echo   checksum ok

mkdir "%WORK%\new" || goto :no_temp
tar.exe -x -f "%WORK%\%NEW_ZIP%" -C "%WORK%\new" || goto :bad_zip
if not exist "%WORK%\new\manifest.json" goto :bad_payload
findstr /c:paliad.de "%WORK%\new\manifest.json" >nul || goto :bad_payload
call :read_field "%WORK%\new\manifest.json" version
if not "%FIELD%"=="%NEW_VER%" goto :bad_payload

rem Nothing in the folder is touched before the download is verified. Everything goes except this
rem script, so a build's renamed chunks cannot accumulate; a file Chrome still holds open survives
rem the delete and stops the run before anything is copied in.
echo   replacing the folder's contents
for /d %%D in ("%TARGET%\*") do rd /s /q "%%~fD" >nul 2>&1
for %%F in ("%TARGET%\*") do if /i not "%%~nxF"=="%~nx0" del /f /q "%%~fF" >nul 2>&1
set "LEFTOVER="
for /d %%D in ("%TARGET%\*") do set "LEFTOVER=1"
for %%F in ("%TARGET%\*") do if /i not "%%~nxF"=="%~nx0" set "LEFTOVER=1"
if defined LEFTOVER goto :locked

xcopy "%WORK%\new\*" "%TARGET%\" /e /i /q /y >nul || goto :copy_failed
if not exist "%TARGET%\manifest.json" goto :copy_failed
call :read_field "%TARGET%\manifest.json" version
if not "%FIELD%"=="%NEW_VER%" goto :copy_failed

rd /s /q "%WORK%" >nul 2>&1
echo.
echo   done - this folder now holds version %SHOW_NEW%.
echo.
echo   Open chrome://extensions and press this extension's reload arrow, or click the
echo   companion's toolbar icon and press the reload it offers.
echo.
echo   Keep this folder and leave the entry in chrome://extensions in place. The pairing with
echo   paliad lives in the entry's profile and goes with it, and only an administrator can
echo   hand out a new one.
echo.
pause
exit /b 0

rem read_field <file> <key> -> FIELD
rem The regex spells each quote as a dot, so the pattern carries no quotes of its own and needs no
rem escaping. "^...version.:" matches `  "version": ...` and not `  "manifest_version": ...`,
rem because the three leading dots cover the indentation and the opening quote exactly.
:read_field
set "FIELD="
for /f "tokens=2 delims=:," %%A in ('findstr /r "^...%~2.:" %1') do set "FIELD=%%A"
set "FIELD=%FIELD: =%"
set FIELD=%FIELD:"=%
exit /b 0

:already_current
rd /s /q "%WORK%" >nul 2>&1
echo.
echo   this folder already holds version %SHOW_NEW%. Nothing to do.
echo.
pause
exit /b 0

:no_tool
echo   REFUSED: curl.exe, certutil.exe and tar.exe must all be on PATH. All three ship
echo            with Windows 10 and 11.
goto :fail

:not_extension
echo   REFUSED: %TARGET% does not hold the Paliad companion. Put this script in the folder
echo            Chrome loaded, beside its manifest.json, and run it from there.
goto :fail

:no_temp
echo   REFUSED: cannot create the working folder %WORK%.
goto :fail

:no_site
echo   FAILED: cannot read %SITE%/latest.json. Check the connection and try again.
goto :fail

:bad_latest
echo   REFUSED: %SITE%/latest.json does not carry a version, a zip name and a sha256
echo            in the form this script reads. Nothing was downloaded.
goto :fail

:no_zip
echo   FAILED: cannot download %SITE%/%NEW_ZIP%.
goto :fail

:zip_too_small
echo   REFUSED: the download is only %ZIP_BYTES% bytes, which is no extension build.
goto :fail

:no_hash
echo   FAILED: certutil did not report a hash for the download.
goto :fail

:bad_checksum
echo   REFUSED: the download does not match the published checksum.
echo            published %NEW_SHA%
echo            download  %ACTUAL%
goto :fail

:bad_zip
echo   FAILED: cannot unpack the download.
goto :fail

:bad_payload
echo   REFUSED: the unpacked build is not version %NEW_VER% of the Paliad companion.
goto :fail

:fail
echo.
echo   Nothing in %TARGET% was changed.
echo.
pause
exit /b 1

:locked
echo   STOPPED: a file in %TARGET% could not be removed, which is Chrome still holding it.
echo            The folder is unchanged. Switch the extension off on chrome://extensions,
echo            run this script again, then switch it back on.
echo.
pause
exit /b 1

:copy_failed
echo   FAILED: the new build could not be copied into %TARGET%, which is now incomplete.
echo           The unpacked build is in %WORK%\new - copy its contents into the folder
echo           by hand, or run this script again.
echo.
pause
exit /b 1
