#!/usr/bin/env bash
set -euo pipefail

gateway_dir=$(cd "$(dirname "$0")" && pwd)
pnpm_bin=${PNPM:-pnpm}
run_root=${REGISTRY_PROOF_ROOT:-${XDG_CACHE_HOME:-$HOME/.cache}/overdeck/tests/registry-gateway/$(date +%Y%m%dT%H%M%S)-$$}
mirror="$run_root/mirror"
fixture="$run_root/fixture"
server_log="$run_root/server.log"
mkdir -p "$mirror" "$fixture"

server_pid=
cleanup() { [[ -z "$server_pid" ]] || kill "$server_pid" 2>/dev/null || true; }
trap cleanup EXIT

public_registry=http://registry.invalid:4873
REGISTRY_MIRROR="$mirror" REGISTRY_PORT=0 REGISTRY_PUBLIC_AUTHORITY=registry.invalid:4873 \
  node "$gateway_dir/server.mjs" >"$server_log" 2>"$run_root/server.err" &
server_pid=$!
for _ in $(seq 1 100); do [[ -s "$server_log" ]] && break; sleep 0.05; done
registry=$(head -n 1 "$server_log")
[[ "$registry" == http://127.0.0.1:*/* ]] || { echo "gateway did not start" >&2; exit 1; }

node - "$registry" <<'JS'
const net = require('node:net');
const proxy = new URL(process.argv[2]);
const socket = net.connect(Number(proxy.port), proxy.hostname, () => {
  socket.write('CONNECT blocked.invalid:80 HTTP/1.1\r\nHost: blocked.invalid:80\r\n\r\n');
});
socket.once('data', (data) => {
  if (!data.toString().startsWith('HTTP/1.1 403 ')) throw new Error(`unexpected CONNECT response: ${data}`);
  socket.destroy();
});
socket.once('error', (error) => { throw error; });
JS
echo 'PASS proxy refuses destinations outside the published registry authority'

make_package() {
  local short_name=$1 version=$2 marker=$3 source="$run_root/source-$1"
  mkdir -p "$source"
  printf '{"name":"@platform-modules/%s","version":"%s","main":"index.js"}\n' "$short_name" "$version" >"$source/package.json"
  printf 'module.exports = "%s";\n' "$marker" >"$source/index.js"
  local archive
  archive=$(npm pack "$source" --pack-destination "$run_root" --silent)
  node "$gateway_dir/admit-package.mjs" "$run_root/$archive" "@platform-modules/$short_name" "$version" "$mirror" "$public_registry" 2020-01-01T00:00:00Z
}

make_package ui-primitives 0.5.0 platform-modules-ui-primitives-proof
make_package query-react 0.1.0 platform-modules-query-react-proof
make_package ui-tokens 0.2.0 platform-modules-ui-tokens-proof

node - "$mirror/packuments/query-react.json" <<'JS'
const { readFileSync } = require('node:fs');
const packument = JSON.parse(readFileSync(process.argv[2], 'utf8'));
if (packument.time?.['0.1.0'] !== '2020-01-01T00:00:00.000Z') {
  throw new Error('admitted packument did not preserve the authenticated publication time');
}
JS
echo 'PASS publication time preserved for minimum-release-age policy'

cat >"$fixture/package.json" <<'JSON'
{"name":"registry-proof","private":true,"dependencies":{"@platform-modules/ui-primitives":"0.5.0","@platform-modules/query-react":"0.1.0","@platform-modules/ui-tokens":"0.2.0"}}
JSON
printf '@platform-modules:registry=%s\n' "$public_registry" >"$fixture/.npmrc"

(cd "$fixture" && HTTP_PROXY="$registry" "$pnpm_bin" install --lockfile-only --store-dir "$run_root/lock-store" --reporter=silent)
rm -rf "$run_root/lock-store"
(cd "$fixture" && HTTP_PROXY="$registry" "$pnpm_bin" install --frozen-lockfile --store-dir "$run_root/cold-store" --reporter=silent)
echo 'PASS frozen cold install (3 packages)'

cp -a "$fixture" "$run_root/url-tamper"
rm -rf "$run_root/url-tamper/node_modules"
perl -0pi -e 's#tarball: https?://[^}]+#tarball: https://tampered.invalid/platform-modules.tgz#' "$run_root/url-tamper/pnpm-lock.yaml"
if (cd "$run_root/url-tamper" && HTTP_PROXY="$registry" "$pnpm_bin" install --frozen-lockfile --store-dir "$run_root/url-store" >"$run_root/url-tamper.log" 2>&1); then
  echo 'FAIL locked tarball URL tamper was accepted' >&2; exit 1
fi
grep -q 'ERR_PNPM_TARBALL_URL_MISMATCH' "$run_root/url-tamper.log" || {
  echo 'FAIL locked tarball URL failed for an unexpected reason' >&2; exit 1;
}
echo 'PASS locked tarball URL tamper failed closed'

cp -a "$fixture" "$run_root/bytes-tamper"
rm -rf "$run_root/bytes-tamper/node_modules"
mapfile -t cached_files < <(grep -rl -- 'platform-modules-ui-primitives-proof' "$run_root/cold-store" || true)
[[ ${#cached_files[@]} -gt 0 ]] || { echo 'FAIL could not locate cached package bytes' >&2; exit 1; }
printf 'tampered\n' >"${cached_files[0]}"
if (cd "$run_root/bytes-tamper" && "$pnpm_bin" install --offline --frozen-lockfile --store-dir "$run_root/cold-store" >"$run_root/bytes-tamper.log" 2>&1); then
  echo 'FAIL cached byte tamper was accepted' >&2; exit 1
fi
echo 'PASS cached byte tamper failed closed (offline)'

status=$(curl -sS -o "$run_root/put-response.json" -w '%{http_code}' -X PUT "${registry}@platform-modules%2Fui-primitives")
[[ "$status" == 405 ]] || { echo "FAIL publish denial returned HTTP $status" >&2; exit 1; }
echo 'PASS PUT/publish denied with HTTP 405'

concurrency=${REGISTRY_PROOF_CONCURRENCY:-50}
start=$(date +%s%N)
pids=()
for worker in $(seq 1 "$concurrency"); do
  worker_dir="$run_root/concurrent/$worker"
  mkdir -p "$worker_dir"
  cp "$fixture/package.json" "$fixture/pnpm-lock.yaml" "$fixture/.npmrc" "$worker_dir/"
  (cd "$worker_dir" && HTTP_PROXY="$registry" timeout 60 "$pnpm_bin" install --frozen-lockfile --store-dir "$run_root/concurrent-store-$worker" --reporter=silent) >"$run_root/concurrent-$worker.log" 2>&1 &
  pids+=("$!")
done
failed=0
for pid in "${pids[@]}"; do wait "$pid" || failed=$((failed + 1)); done
elapsed_ms=$(( ($(date +%s%N) - start) / 1000000 ))
[[ $failed -eq 0 ]] || { echo "FAIL concurrent cold installs: $failed/$concurrency failed in ${elapsed_ms}ms" >&2; exit 1; }
echo "PASS concurrent cold installs: $concurrency/$concurrency in ${elapsed_ms}ms ($concurrency isolated stores)"
echo "Evidence retained at $run_root"
