#!/usr/bin/env bash
# @comment -- "Bootstrap the pinned upstream tools on a fresh Actions runner: the released npm and crates.io versions, or, when a pin names a revision, that commit built from source."
set -euo pipefail
role=${1:?choose author or replay}
case "$role" in author|replay|annotate) ;; *) exit 2 ;; esac
pins="$(dirname "$0")/proof-tool-pins.json"
guardlink_version=$(jq -er '.guardlink.version' "$pins")
guardlink_revision=$(jq -r '.guardlink.revision // empty' "$pins")
guardlink_repo=$(jq -er '.guardlink.repository' "$pins")
cxg_version=$(jq -er '.cxg.version' "$pins")
cxg_revision=$(jq -r '.cxg.revision // empty' "$pins")
cxg_repo=$(jq -er '.cxg.repository' "$pins")
# Every job uses the same GuardLink: the replay and annotate jobs read the model the author wrote against.
if test -n "$guardlink_revision"; then
  source_dir=$(mktemp -d "$RUNNER_TEMP/bravos-guardlink-XXXXXX")
  git init -q "$source_dir"
  git -C "$source_dir" fetch --quiet --depth=1 "$guardlink_repo" "$guardlink_revision"
  git -C "$source_dir" checkout --quiet --detach FETCH_HEAD
  test "$(git -C "$source_dir" rev-parse HEAD)" = "$guardlink_revision"
  (
    cd "$source_dir"
    npm ci --include=dev --no-audit --no-fund
    npm run build
    tarball=$(npm pack --ignore-scripts --json | jq -re '.[0].filename')
    npm install -g "./$tarball"
  )
else
  npm install -g "guardlink@$guardlink_version"
fi
test "$role" != annotate || exit 0
install_root="$RUNNER_TEMP/bravos-cxg"
if ! test -x "$install_root/bin/cxg"; then
  if test -n "$cxg_revision"; then
    cargo install --locked --root "$install_root" --git "$cxg_repo" --rev "$cxg_revision" cert-x-gen
  else
    cargo install --locked --root "$install_root" "cert-x-gen@$cxg_version"
  fi
fi
export PATH="$install_root/bin:$PATH"
echo "$install_root/bin" >> "$GITHUB_PATH"
# Bravos runs cxg only through `cxg scan`: the first scan installs or refreshes cxg's embedded pipeline
# itself. The replay runner needs that pipeline's Python dependencies, taken from the cxg source the
# pinned binary was built from (its tag, or the pinned revision).
if test "$role" = replay; then
  cxg_ref=${cxg_revision:-v$cxg_version}
  requirements="$RUNNER_TEMP/cxg-requirements.txt"
  curl --fail --silent --show-error --location --proto '=https' \
    "https://raw.githubusercontent.com/Bugb-Technologies/cert-x-gen/$cxg_ref/pentest/requirements.txt" -o "$requirements"
  "$CXG_PYTHON" -m pip install -r "$requirements"
  "$CXG_PYTHON" -m playwright install --with-deps chromium
fi
