#!/usr/bin/env bash
# build-lavamoat.sh — one-shot production-like Extension build for live proof
set -euo pipefail

TARGET="$PWD"
RUNTIME_DIR="temp/recipe/runtime"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --target) [ "$#" -ge 2 ] || { echo "Missing value for $1" >&2; exit 2; }; TARGET="$2"; shift 2 ;;
    --runtime-dir) [ "$#" -ge 2 ] || { echo "Missing value for $1" >&2; exit 2; }; RUNTIME_DIR="$2"; shift 2 ;;
    -h|--help) echo "Usage: build-lavamoat.sh [--target <metamask-extension>] [--runtime-dir <relative path>]"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
for _arn in "$SCRIPT_DIR/lib/activate-repo-node.sh" "$SCRIPT_DIR/../shared/activate-repo-node.sh"; do
  [ -f "$_arn" ] && { # shellcheck disable=SC1090
    . "$_arn"
    break
  }
done
unset _arn

TARGET="$(cd "$TARGET" && pwd)"
cd "$TARGET"
if command -v require_repo_node >/dev/null 2>&1; then
  require_repo_node "$TARGET"
elif command -v activate_repo_node >/dev/null 2>&1; then
  activate_repo_node "$TARGET"
else
  echo "build-lavamoat: activate-repo-node.sh missing from harness; run: mm-harness install" >&2
  exit 1
fi

for pid_file in "$RUNTIME_DIR/webpack.pid" "$RUNTIME_DIR/recipe-harness-webpack.pid"; do
  [ -f "$pid_file" ] || continue
  pid="$(cat "$pid_file" 2>/dev/null || true)"
  if [ -n "$pid" ] && kill -0 "$pid" >/dev/null 2>&1; then
    echo "build-lavamoat: a webpack watcher already owns this checkout (pid $pid). Next: stop the slot watcher and retry." >&2
    exit 1
  fi
  rm -f "$pid_file"
done

# A one-shot build has no watch health to report. Remove logs left by a dead
# watcher so readiness does not mistake an old failure for the current build.
rm -f "$RUNTIME_DIR/webpack.log" "$RUNTIME_DIR/recipe-harness-webpack.log"

echo "[recipe-harness] clean non-test LavaMoat build"
rm -rf node_modules/.cache/webpack
yarn webpack:tsc
METAMASK_DEBUG=true yarn webpack:lavamoat:build
test -f dist/chrome/manifest.json || {
  echo "build-lavamoat: build completed without dist/chrome/manifest.json" >&2
  exit 1
}
echo "[recipe-harness] non-test LavaMoat build completed"
