#!/usr/bin/env bash
set -u
set -o pipefail

SOURCE_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
EVIDENCE_DIR="$SOURCE_DIR/evidence"
RUN_ID="run-$(date -u +%Y%m%dT%H%M%SZ)-$$"
WORK_DIR=$(mktemp -d "${TMPDIR:-/var/tmp}/pdf2html-auth-consumer.XXXXXX")
NPMRC=${NPM_CONFIG_USERCONFIG:-"$(CDPATH= cd -- "$SOURCE_DIR/../../.." && pwd -P)/.npmrc"}
export NPM_CONFIG_USERCONFIG="$NPMRC"
mkdir -p "$EVIDENCE_DIR"
rm -f "$EVIDENCE_DIR"/*

cleanup() { rm -rf "$WORK_DIR"; }
trap cleanup EXIT

# Copy only the standalone consumer inputs; never use the ancestor checkout as npm's project root.
tar -C "$SOURCE_DIR" --exclude=evidence --exclude=node_modules --exclude=dist --exclude=package-lock.json -cf - . | tar -C "$WORK_DIR" -xf -

printf '%s\n' \
  'NPM_CONFIG_USERCONFIG=<remote configured npmrc> npm install --ignore-scripts --workspaces=false' \
  'npm ls --all --json' \
  'npm run typecheck' \
  'npm test -- --reporter=verbose' \
  'npm run build' > "$EVIDENCE_DIR/command-manifest.redacted.txt"

{
  printf 'run_id=%s\n' "$RUN_ID"
  printf 'utc_started=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf 'hostname=%s\n' "$(hostname)"
  printf 'kernel=%s\n' "$(uname -srmo)"
  printf 'node=%s\n' "$(node --version)"
  printf 'npm=%s\n' "$(npm --version)"
  printf 'source=%s\n' "$SOURCE_DIR"
  printf 'isolated_workdir=%s\n' "$WORK_DIR"
  printf 'ancestor_workspace_inherited=false\n'
} > "$EVIDENCE_DIR/run-metadata.txt"
npm config get @platform-modules:registry > "$EVIDENCE_DIR/npm-registry-resolution.txt"

status_file="$EVIDENCE_DIR/exit-statuses.txt"
: > "$status_file"
run_phase() {
  phase=$1; shift
  set +e
  (cd "$WORK_DIR" && "$@") >"$EVIDENCE_DIR/${phase}.stdout.log" 2>"$EVIDENCE_DIR/${phase}.stderr.log"
  status=$?
  set -e
  printf '%s=%s\n' "$phase" "$status" >> "$status_file"
  return "$status"
}

set -e
run_phase install npm install --ignore-scripts --workspaces=false || exit $?
cp "$WORK_DIR/package-lock.json" "$EVIDENCE_DIR/package-lock.json"
run_phase npm-ls npm ls --all --json || exit $?
cp "$EVIDENCE_DIR/npm-ls.stdout.log" "$EVIDENCE_DIR/dependency-tree.json"
run_phase typecheck npm run typecheck || exit $?
run_phase test npm test -- --reporter=verbose || exit $?
run_phase build npm run build || exit $?
(cd "$WORK_DIR" && find dist -type f -print0 | sort -z | xargs -0 sha256sum) > "$EVIDENCE_DIR/build-artifacts.sha256"
(cd "$EVIDENCE_DIR" && sha256sum package-lock.json dependency-tree.json *.log build-artifacts.sha256) > "$EVIDENCE_DIR/checksums.sha256"
printf 'utc_finished=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$EVIDENCE_DIR/run-metadata.txt"
