#!/usr/bin/env bash
# uninstall.sh — Remove a previously installed Orb instance
#
# Detects whether the current installation is system-wide (/opt/orb) or
# user-local (~/.local/share/orb) and removes all installed artifacts.
# User configuration and data (~/.config/orb, ~/.local/share/orb/logs/)
# are preserved by default unless --purge is passed.
#
# Usage:
#   ./packaging/uninstall.sh           # auto-detect and uninstall
#   ./packaging/uninstall.sh --system  # force system-wide uninstall
#   ./packaging/uninstall.sh --user    # force user-local uninstall
#   ./packaging/uninstall.sh --purge   # also delete user data/config
#   ./packaging/uninstall.sh --help

set -euo pipefail

# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
MAGENTA='\033[0;35m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

log_step()  { echo -e "\n${BOLD}${MAGENTA}▶ $*${NC}"; }
log_info()  { echo -e "  ${CYAN}•${NC} $*"; }
log_ok()    { echo -e "  ${GREEN}✓${NC} $*"; }
log_warn()  { echo -e "  ${YELLOW}⚠${NC} $*"; }
log_error() { echo -e "  ${RED}✗ ERROR:${NC} $*" >&2; }
log_skip()  { echo -e "  ${YELLOW}–${NC} $* (not found, skipping)"; }

# ── Args ──────────────────────────────────────────────────────────────────────
PREFIX_MODE=""
PURGE=false

for arg in "$@"; do
    case "${arg}" in
        --system)  PREFIX_MODE="system" ;;
        --user)    PREFIX_MODE="user" ;;
        --purge)   PURGE=true ;;
        --help|-h)
            sed -n '2,/^[^#]/{ /^#/p }' "${BASH_SOURCE[0]}" | sed 's/^# \?//'
            exit 0
            ;;
        *)
            log_error "Unknown argument: ${arg}"
            echo "Usage: $0 [--system|--user] [--purge] [--help]"
            exit 1
            ;;
    esac
done

# ── Auto-detect install mode ──────────────────────────────────────────────────
if [[ -z "${PREFIX_MODE}" ]]; then
    if [[ -d "/opt/orb" ]]; then
        PREFIX_MODE="system"
    elif [[ -d "${HOME}/.local/share/orb" ]] && \
         [[ -f "${HOME}/.local/share/orb/orb" ]]; then
        PREFIX_MODE="user"
    else
        log_error "No Orb installation detected."
        echo "  Checked: /opt/orb and ${HOME}/.local/share/orb"
        echo "  Use --system or --user to override."
        exit 1
    fi
    log_info "Auto-detected install mode: ${BOLD}${PREFIX_MODE}${NC}"
fi

# ── Derive paths ──────────────────────────────────────────────────────────────
if [[ "${PREFIX_MODE}" == "system" ]]; then
    BUNDLE_DEST="/opt/orb"
    BIN_DIR="/usr/bin"
    SYSTEMD_UNIT_DIR="/usr/lib/systemd/user"
    UDEV_RULES_FILE="/usr/lib/udev/rules.d/70-orb-input.rules"
    DESKTOP_FILE="/usr/share/applications/orb.desktop"
    ICON_BASE="/usr/share/icons/hicolor"
    NEED_SUDO=true
else
    BUNDLE_DEST="${HOME}/.local/share/orb"
    BIN_DIR="${HOME}/.local/bin"
    SYSTEMD_UNIT_DIR="${HOME}/.config/systemd/user"
    UDEV_RULES_FILE="/usr/lib/udev/rules.d/70-orb-input.rules"
    DESKTOP_FILE="${HOME}/.local/share/applications/orb.desktop"
    ICON_BASE="${HOME}/.local/share/icons/hicolor"
    NEED_SUDO=false
fi

# ── sudo helper ───────────────────────────────────────────────────────────────
_sudo() {
    if ${NEED_SUDO}; then sudo "$@"; else "$@"; fi
}

_sudo_if_exists() {
    local f="$1"; shift
    if [[ -e "${f}" ]]; then
        _sudo "$@"
    fi
}

# ── Banner ────────────────────────────────────────────────────────────────────
echo
echo -e "${BOLD}${MAGENTA}╔══════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${MAGENTA}║        Orb Uninstaller                   ║${NC}"
echo -e "${BOLD}${MAGENTA}╚══════════════════════════════════════════╝${NC}"
echo
echo -e "  Mode   : ${BOLD}${PREFIX_MODE}${NC}"
echo -e "  Bundle : ${BUNDLE_DEST}"
if ${PURGE}; then
    echo -e "  ${RED}${BOLD}--purge: user data and config will also be deleted${NC}"
fi
echo

read -rp "  Proceed with uninstall? [y/N] " confirm
[[ "${confirm,,}" == "y" ]] || { echo "  Aborted."; exit 0; }

# ── Step 1: Stop and disable systemd service ─────────────────────────────────
log_step "Stopping orb-daemon service"

if systemctl --user is-active --quiet orb-daemon.service 2>/dev/null; then
    systemctl --user stop orb-daemon.service
    log_ok "orb-daemon stopped"
else
    log_skip "orb-daemon service (not running)"
fi

systemctl --user disable orb-daemon.service 2>/dev/null || true
systemctl --user daemon-reload 2>/dev/null || true
log_ok "Service disabled"

# ── Step 2: Remove service unit file ─────────────────────────────────────────
log_step "Removing systemd unit"

UNIT_FILE="${SYSTEMD_UNIT_DIR}/orb-daemon.service"
if [[ -f "${UNIT_FILE}" ]]; then
    _sudo rm -f "${UNIT_FILE}"
    systemctl --user daemon-reload 2>/dev/null || true
    log_ok "Removed: ${UNIT_FILE}"
else
    log_skip "${UNIT_FILE}"
fi

# ── Step 3: Remove udev rules ─────────────────────────────────────────────────
log_step "Removing udev rules"

if [[ -f "${UDEV_RULES_FILE}" ]]; then
    sudo rm -f "${UDEV_RULES_FILE}"
    sudo udevadm control --reload-rules 2>/dev/null || true
    sudo udevadm trigger --subsystem-match=input 2>/dev/null || true
    log_ok "Removed: ${UDEV_RULES_FILE}"
else
    log_skip "${UDEV_RULES_FILE}"
fi

# ── Step 4: Remove .desktop file ─────────────────────────────────────────────
log_step "Removing .desktop entry"

if [[ -f "${DESKTOP_FILE}" ]]; then
    _sudo rm -f "${DESKTOP_FILE}"
    if command -v update-desktop-database &>/dev/null; then
        _sudo update-desktop-database "$(dirname "${DESKTOP_FILE}")" 2>/dev/null || true
    fi
    log_ok "Removed: ${DESKTOP_FILE}"
else
    log_skip "${DESKTOP_FILE}"
fi

# ── Step 5: Remove icons ──────────────────────────────────────────────────────
log_step "Removing icons"

removed_icons=false
for size in 16 32 48 64 128 256; do
    icon="${ICON_BASE}/${size}x${size}/apps/orb.png"
    if [[ -f "${icon}" ]]; then
        _sudo rm -f "${icon}"
        removed_icons=true
    fi
done

if ${removed_icons}; then
    if command -v gtk-update-icon-cache &>/dev/null; then
        _sudo gtk-update-icon-cache -f -t "${ICON_BASE}" 2>/dev/null || true
    fi
    log_ok "Icons removed and cache updated"
else
    log_skip "Icons (none found in ${ICON_BASE})"
fi

# ── Step 5b: Remove ld.so.conf.d entry (system install only) ─────────────────
log_step "Removing ld.so.conf.d entry"

LD_CONF_FILE="/etc/ld.so.conf.d/orb.conf"
if [[ -f "${LD_CONF_FILE}" ]]; then
    sudo rm -f "${LD_CONF_FILE}"
    sudo ldconfig 2>/dev/null || true
    log_ok "Removed: ${LD_CONF_FILE}"
else
    log_skip "${LD_CONF_FILE}"
fi

# ── Step 6: Remove CLI wrapper and daemon binary ──────────────────────────────
log_step "Removing binaries"

for f in "${BIN_DIR}/orb" "${BIN_DIR}/orb-daemon"; do
    if [[ -f "${f}" || -L "${f}" ]]; then
        _sudo rm -f "${f}"
        log_ok "Removed: ${f}"
    else
        log_skip "${f}"
    fi
done

# ── Step 7: Remove bundle ─────────────────────────────────────────────────────
log_step "Removing Flutter bundle"

if [[ -d "${BUNDLE_DEST}" ]]; then
    _sudo rm -rf "${BUNDLE_DEST}"
    log_ok "Removed: ${BUNDLE_DEST}"
else
    log_skip "${BUNDLE_DEST}"
fi

# ── Step 8: Optionally purge user data ───────────────────────────────────────
if ${PURGE}; then
    log_step "Purging user data (--purge)"

    for d in \
        "${HOME}/.config/orb" \
        "${HOME}/.local/share/orb"
    do
        if [[ -d "${d}" ]]; then
            rm -rf "${d}"
            log_ok "Purged: ${d}"
        else
            log_skip "${d}"
        fi
    done
else
    echo
    log_warn "User data preserved:"
    for d in "${HOME}/.config/orb" "${HOME}/.local/share/orb"; do
        [[ -d "${d}" ]] && echo -e "    ${CYAN}${d}${NC}"
    done
    echo -e "  Run with ${BOLD}--purge${NC} to delete these as well."
fi

# ── Done ─────────────────────────────────────────────────────────────────────
echo
echo -e "${BOLD}${GREEN}  Orb has been uninstalled.${NC}"
echo
