#!/usr/bin/env bash

BRT_INSTALL_DIR="${BRT_DIR:-${BRT_INSTALL_DIR:-${HOME}/.local/share/brt}}"
BRT_BIN_DIR="${BRT_BIN_DIR:-${HOME}/.local/bin}"
BRT_STATE_DIR="${HOME}/.brt"

brt_uninstall_confirm() {
  printf "Uninstall brt and remove packages it installed? [Y/n] "
  read -r ans
  [[ -z "$ans" || "$ans" =~ ^[Yy]$ ]]
}

brt_uninstall() {
  brt_info "Removing brt..."

  if ! brt_uninstall_confirm; then
    brt_info "Uninstall cancelled"
    return 0
  fi

  # Stop any access servers
  if [[ -f "${BRT_LIB}/access.sh" ]]; then
    # shellcheck source=access.sh
    source "${BRT_LIB}/access.sh"
    brt_access_force_stop 2>/dev/null || true
  elif [[ -f "${BRT_STATE_DIR}/access.pid" ]]; then
    local pid
    pid=$(tr -d '[:space:]' < "${BRT_STATE_DIR}/access.pid" 2>/dev/null || true)
    if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
      kill "$pid" 2>/dev/null || true
      brt_info "Stopped access server (PID ${pid})"
    fi
  fi

  # Remove packages brt installed (tracked in ~/.brt/installed-deps)
  if [[ -f "${BRT_LIB}/deps.sh" ]]; then
    # shellcheck source=deps.sh
    source "${BRT_LIB}/deps.sh"
    brt_uninstall_media_dependencies || true
  fi

  # Remove symlink
  if [[ -L "${BRT_BIN_DIR}/brt" || -f "${BRT_BIN_DIR}/brt" ]]; then
    rm -f "${BRT_BIN_DIR}/brt"
    brt_ok "Removed ${BRT_BIN_DIR}/brt"
  fi

  # Remove install directory
  if [[ -d "$BRT_INSTALL_DIR" ]]; then
    rm -rf "$BRT_INSTALL_DIR"
    brt_ok "Removed ${BRT_INSTALL_DIR}"
  fi

  # Remove state/config
  if [[ -d "$BRT_STATE_DIR" ]]; then
    rm -rf "$BRT_STATE_DIR"
    brt_ok "Removed ${BRT_STATE_DIR}"
  fi

  brt_ok "brt uninstalled"
  # shellcheck source=update.sh
  source "${BRT_LIB}/update.sh"
  brt_remove_startup_check_hook || true
  brt_info "Removed startup update checks from shell config"
  brt_info "PATH entries in shell rc files were left unchanged"
}
