#!/bin/sh
# Re-runs the evidence for fix(desktop): Windows updates wait out a signature check slowed by antivirus.
# FIX: checkout of fix/windows-signature-check-timeout. PR: checkout of pull/25945/head (1d57f68aa8).
# Both need `vp i --frozen-lockfile`. Runs on macOS/Linux; no Windows or PowerShell is involved.
# Side effects: recreates upstream/ and apply-check/ next to this script (npm pack downloads),
# runs `vp i --frozen-lockfile` in FIX, and overwrites the .log files here.
set -eu
FIX=${FIX:?checkout of the fix branch}
PR=${PR:?checkout of pull/25945/head}
P=$(cd "$(dirname "$0")" && pwd)

# 1. Upstream still hard-codes 20 s in 6.8.x; 7.0.0-alpha.13 (fail-closed rewrite) uses 60 s.
for v in 6.8.9 6.8.11 6.8.12 7.0.0-alpha.13; do
  d="$P/upstream/eu-$v"; rm -rf "$d"; mkdir -p "$d"
  (cd "$d" && npm pack "electron-updater@$v" --silent >/dev/null && tar -xzf "electron-updater-$v.tgz")
done
(cd "$P" && grep -H -o 'ConvertTo-Json -Compress"`, [0-9]* \* 1000' upstream/eu-6.8.*/package/out/windowsExecutableCodeSignatureVerifier.js
  grep -H 'const VERIFY_TIMEOUT_MS' upstream/eu-7.0.0-alpha.13/package/dist/windowsExecutableCodeSignatureVerifier.js) | tee "$P/upstream/upstream-literal.log"

# 2. The patch applies to the npm tarball, and pnpm accepts the lockfile.
rm -rf "$P/apply-check" && mkdir "$P/apply-check" && cp -R "$P/upstream/eu-6.8.9/package" "$P/apply-check/pkg"
(cd "$P/apply-check/pkg" && git apply --check "$FIX/patches/electron-updater@6.8.9.patch")
(cd "$FIX" && vp i --frozen-lockfile)

# 3. The installed verifier passes {timeout: 120000, shell: true} on the fix and 20000 on #25945;
#    POSIX analog of the cmd.exe/powershell orphan, and execFileSync blocking the event loop.
node "$P/verifier-timeout-and-orphan.cjs" "$P" "$FIX" "$PR" | tee "$P/verifier-timeout-and-orphan.log"

# 4. Simulated download: each checkout's real ElectronUpdater.downloadUpdate over its real installed
#    verifier. The header of signature-probe-count.mjs lists what is stubbed (Electron, the verifier
#    wiring, the download step, execFile, execFileSync). Reports checks, probes and timed-out checks.
for s in always-timeout scan-done-55.8s; do
  node "$P/signature-probe-count.mjs" "$PR" pr25945-head "$s"
  node "$P/signature-probe-count.mjs" "$FIX" this-branch "$s"
done | tee "$P/signature-probe-count.log"
