#!/usr/bin/env bash
# Remove checkout-local Mobile harness metadata without touching product source.
set -euo pipefail

TARGET="$PWD"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --target) [ "$#" -ge 2 ] || { echo "Missing value for --target" >&2; exit 2; }; TARGET="$2"; shift 2 ;;
    -h|--help) echo "Usage: cleanup.sh [--target <metamask-mobile>]"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$SCRIPT_DIR/../shared/harness-path.sh"
TARGET="$(cd "$TARGET" && pwd -P)"
HARNESS_DIR="$(harness_dir "$TARGET" mobile)"

pkill -f "console-forwarder.cjs --port .* --out $TARGET/" 2>/dev/null || true

tracking_file="$HARNESS_DIR/added-git-exclude"
if [ -s "$tracking_file" ]; then
  git_dir="$(git -C "$TARGET" rev-parse --git-dir 2>/dev/null || true)"
  if [ -n "$git_dir" ]; then
    case "$git_dir" in /*) ;; *) git_dir="$TARGET/$git_dir" ;; esac
    exclude_file="$git_dir/info/exclude"
    if [ -f "$exclude_file" ]; then
      tmp_file="$(mktemp)"
      awk 'NR==FNR { if (length($0)) drop[$0]=1; next } !($0 in drop)' "$tracking_file" "$exclude_file" > "$tmp_file"
      mv "$tmp_file" "$exclude_file"
    fi
  fi
fi

rm -rf "$HARNESS_DIR"
echo "Cleaned mobile harness metadata from $TARGET; product files were not touched"
