#!/usr/bin/env sh
set -eu

INSTALL_ROOT="${BMCLI_INSTALL_ROOT:-$HOME/.local/share/bmcli}"
BIN_ROOT="${BMCLI_BIN_ROOT:-$HOME/.local/bin}"
MAN_ROOT="${BMCLI_MAN_ROOT:-$HOME/.local/share/man/man1}"
KEEP_AI=0
REMOVE_UDEV=0

while [ "$#" -gt 0 ]; do
    case "$1" in
        --install-root) INSTALL_ROOT="$2"; shift 2 ;;
        --bin-root) BIN_ROOT="$2"; shift 2 ;;
        --man-root) MAN_ROOT="$2"; shift 2 ;;
        --keep-ai) KEEP_AI=1; shift ;;
        --remove-udev) REMOVE_UDEV=1; shift ;;
        --help|-h) echo "Usage: uninstall.sh [--keep-ai] [--remove-udev] [--install-root DIR]"; exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

remove_owned_link() {
    link=$1
    if [ -L "$link" ]; then
        target=$(readlink "$link")
        case "$target" in "$INSTALL_ROOT"/*) rm -f "$link" ;; esac
    fi
}

# Stop the per-user daemon while its binary and PID state are still available.
# Removing an active installation first would leave a live process mapped from
# a deleted executable and make later installs connect to stale runtime state.
if [ -x "$BIN_ROOT/bmcli" ]; then
    "$BIN_ROOT/bmcli" daemon stop >/dev/null 2>&1 || true
elif [ -x "$INSTALL_ROOT/current/bin/bmcli" ]; then
    "$INSTALL_ROOT/current/bin/bmcli" daemon stop >/dev/null 2>&1 || true
fi

remove_owned_link "$BIN_ROOT/bmcli"
remove_owned_link "$MAN_ROOT/bmcli.1"
rm -rf "$INSTALL_ROOT"

if [ "$KEEP_AI" -eq 0 ]; then
    rm -rf "${AGENTS_HOME:-$HOME/.agents}/skills/bmcli"
    rm -rf "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/bmcli"
fi

if [ "$REMOVE_UDEV" -eq 1 ]; then
    command -v sudo >/dev/null 2>&1 || { echo "sudo is required for --remove-udev" >&2; exit 1; }
    sudo rm -f /etc/udev/rules.d/99-busmust.rules
    sudo udevadm control --reload-rules
    sudo udevadm trigger --subsystem-match=usb
fi

echo "BMCLI was removed."
