#!/bin/bash
# Cleanup script for Codex Launcher - kills only launcher-owned processes.

set -u

REGISTRY="${HOME}/.cache/codex-launcher/pids.json"

echo "Cleaning up launcher-owned processes..." >&2

kill_group() {
  kind="$1"
  pgid="$2"

  if [ -z "$pgid" ] || [ "$pgid" = "null" ]; then
    return 0
  fi

  if kill -TERM -- "-$pgid" 2>/dev/null; then
    echo "  Stopped ${kind} pgid=${pgid}"
    return 0
  fi

  return 0
}

if [ -f "$REGISTRY" ]; then
  python3 - "$REGISTRY" <<'PY'
import json, sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    data = json.loads(path.read_text())
except Exception:
    data = {}

for kind, meta in sorted(data.items()):
    pgid = meta.get('pgid') if isinstance(meta, dict) else None
    if pgid:
        print(f'{kind}\t{pgid}')
PY
else
  echo "  No registry found; nothing to stop"
fi | while IFS=$'\t' read -r kind pgid; do
  [ -n "${kind:-}" ] || continue
  kill_group "$kind" "$pgid"
done

rm -f "$HOME/.codex/.launch-action-socket" 2>/dev/null || true
rm -f "$HOME/.codex/.codex-desktop-launch-action" 2>/dev/null || true
rm -f "$HOME/.local/share/codex-desktop/.launch-action-socket" 2>/dev/null || true
rm -f "$HOME/.cache/codex-desktop/.launch-action-socket" 2>/dev/null || true
rm -f "$HOME/.local/share/codex-desktop/.codex-desktop-pid" 2>/dev/null || true
rm -f "$HOME/.cache/codex-desktop/.codex-desktop-pid" 2>/dev/null || true
rm -f "$HOME/.local/share/codex-desktop/.webview-pid" 2>/dev/null || true
rm -f "$HOME/.cache/codex-desktop/.webview-pid" 2>/dev/null || true

echo "Cleanup complete"
