#!/usr/bin/env bash
# stop-viewers.sh — close extension tmux viewers and console tail for one checkout.
set -euo pipefail

TARGET="$PWD"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --target) TARGET="$2"; shift 2 ;;
    -h|--help) echo "Usage: stop-viewers.sh [--target <metamask-extension>]"; exit 0 ;;
    *) echo "stop-viewers: unknown arg: $1" >&2; exit 2 ;;
  esac
done

TARGET="$(cd "$TARGET" && pwd)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
for _hp in "$SCRIPT_DIR/lib/harness-path.sh" "$SCRIPT_DIR/../shared/harness-path.sh"; do
  [ -f "$_hp" ] && { . "$_hp"; break; }
done
unset _hp
if ! command -v recipe_runtime_dir >/dev/null 2>&1; then
  echo "stop-viewers: shared lib harness-path.sh not found; reinstall the runner." >&2
  exit 1
fi
# shellcheck disable=SC1091
for _tv_src in "$SCRIPT_DIR/lib/tmux-viewer.sh" "$SCRIPT_DIR/../shared/tmux-viewer.sh"; do
  [ -f "$_tv_src" ] && { . "$_tv_src"; break; }
done
unset _tv_src

runtime_dir="$TARGET/$(recipe_runtime_dir)"
console_log="$runtime_dir/extension-console.log"
set +e

if command -v tmux_viewer_close_marker >/dev/null 2>&1; then
  tmux_viewer_close_marker "$runtime_dir/webpack.tmux"
  tmux_viewer_close_marker "$runtime_dir/console.tmux"
fi
if command -v tmux_viewer_sweep_prefix >/dev/null 2>&1; then
  tmux_viewer_sweep_prefix "webpack" "$runtime_dir"
  tmux_viewer_sweep_prefix "console" "$runtime_dir"
fi

ps -axo pid=,command= 2>/dev/null | while read -r pid command; do
  [ -n "${pid:-}" ] || continue
  case "$command" in
    *console-tail.mjs*) ;;
    *) continue ;;
  esac
  case "$command" in
    *"--log $console_log"*|*"$console_log"*) kill "$pid" 2>/dev/null || true ;;
  esac
done

rm -f "$runtime_dir/console.tmux" "$runtime_dir/webpack.tmux" "$runtime_dir/console-tail.pid"
exit 0
