#!/bin/bash
#
# Purpose : HamPack uninstaller

print_logo() {
  cat << "EOF"



 ██╗  ██╗ █████╗ ███╗   ███╗██████╗  █████╗  ██████╗██╗  ██╗
 ██║  ██║██╔══██╗████╗ ████║██╔══██╗██╔══██╗██╔════╝██║ ██╔╝
 ███████║███████║██╔████╔██║██████╔╝███████║██║     █████╔╝
 ██╔══██║██╔══██║██║╚██╔╝██║██╔═══╝ ██╔══██║██║     ██╔═██╗
 ██║  ██║██║  ██║██║ ╚═╝ ██║██║     ██║  ██║╚██████╗██║  ██╗
 ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝     ╚═╝╚═╝     ╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝




EOF
}

COREDESKTOP="$HOME/.local/share/coredesktop"
APPLICATIONS_DIR="$HOME/.local/share/applications"
BIN="$HOME/.local/bin"

# Print the path of the HamPack clone that `sibling add` made
find_hampack_dir() {
  local dir
  for dir in "$HOME"/.local/share/siblings/*/; do
    [ -d "$dir/.git" ] || continue
    if [[ "$(git -C "$dir" remote get-url origin 2> /dev/null)" =~ /[Hh]am[Pp]ack(\.git)?/?$ ]]; then
      echo "${dir%/}"
      return 0
    fi
  done
  return 1
}

# Remove a file, with sudo if it's outside your home
remove_file() {
  if [[ "$1" == "$HOME"/* ]]; then
    rm -f "$1"
  else
    sudo rm -f "$1"
  fi
}

# Remove the files install_staged recorded for each app it installed
remove_manifests() {
  local manifest file
  for manifest in "$HAMPACK_STATE"/manifests/*; do
    [ -f "$manifest" ] || continue
    while IFS= read -r file; do
      [ -n "$file" ] && remove_file "$file"
    done < "$manifest"
  done
}

# parse_conf callbacks: remove each app's binary and desktop file
remove_binary_app() {
  rm -f "$(expand_vars "${CONF[install]}")"
  [ "${CONF[gui]}" = "true" ] && rm -f "$APPLICATIONS_DIR/${CONF[_name]}.desktop"
  return 0
}
remove_compiled_app() {
  rm -f "$(expand_vars "${CONF[install]}")"
  [ -n "${CONF[desktop]}" ] && rm -f "$APPLICATIONS_DIR/$(basename "${CONF[desktop]}")"
  return 0
}

# Files from builds made before HamPack recorded what builds install
remove_unrecorded_build_files() {
  local name
  # direwolf
  for name in direwolf decode_aprs text2tt tt2text ll2utm utm2ll aclients log2gpx gen_packets \
      atest ttcalc kissutil tnctest appserver cm108 dwespeak.sh telem-balloon.pl telem-bits.pl \
      telem-data.pl telem-data91.pl telem-eqns.pl telem-parm.pl telem-seq.sh telem-unit.pl telem-volts.py; do
    rm -f "$BIN/$name"
  done
  rm -f "$BIN"/direwolf-*
  for name in direwolf decode_aprs kissutil aclients atest gen_packets ll2utm log2gpx text2tt tt2text utm2ll; do
    rm -f "$HOME/.local/share/man/man1/$name.1"
  done
  rm -rf "$HOME/.local/share/direwolf" "$HOME/.local/share/doc/direwolf"
  rm -f "$APPLICATIONS_DIR/direwolf.desktop" "$HOME/.local/share/pixmaps/direwolf_icon.png"
  sudo rm -f /etc/udev/rules.d/99-direwolf-cmedia.rules
  # kiwix-desktop and kiwix-tools
  rm -f "$BIN"/kiwix-desktop "$BIN"/kiwix-serve "$BIN"/kiwix-manage "$BIN"/kiwix-search "$BIN"/kiwix-lib
  rm -f "$HOME"/.local/share/man/man1/kiwix-*.1 "$HOME"/.local/share/man/*/man1/kiwix-*.1
  rm -f "$APPLICATIONS_DIR/org.kiwix.desktop.desktop" "$HOME/.local/share/metainfo/org.kiwix.desktop.appdata.xml"
  rm -f "$HOME"/.local/share/icons/hicolor/*/apps/kiwix-desktop.* "$HOME"/.local/share/icons/hicolor/*/mimetypes/org.kiwix.desktop.*
  rm -f "$HOME/.local/share/mime/packages/org.kiwix.desktop-mime.xml"
  # graywolf, yaac, paracon
  rm -f "$BIN/graywolf-modem"
  rm -rf "$HOME/.local/share/graywolf" "$BIN/yaac"
  rm -f "$BIN"/paracon_*.pyz
  return 0
}

remove_graywolf_service() {
  [ -f /etc/systemd/system/graywolf.service ] || return 0
  sudo systemctl disable --now graywolf
  sudo rm -f /etc/systemd/system/graywolf.service
  sudo systemctl daemon-reload
}

remove_wine_apps() {
  local prefix="${WINEPREFIX:-$HOME/.wine}"
  [ -d "$prefix" ] || return 0

  rm -rf "$prefix/drive_c/VARA" "$prefix/drive_c/VARA FM" "$prefix/drive_c/RMS Express"
  rm -f "$HAMPACK_STATE/wine-deps-installed"

  if [ -f "$HAMPACK_STATE/wine-prefix-created" ]; then
    read -rp "HamPack created the Wine prefix $prefix. Remove it, with anything else installed in it? [y/N] " answer
    if [[ "$answer" =~ ^[yY] ]]; then
      rm -rf "$prefix"
      return 0
    fi
  fi
  if command -v wine &> /dev/null; then
    wine reg delete 'HKCU\Software\Wine\X11 Driver' /v Decorated /f &> /dev/null
  fi
  return 0
}

# Remove the packages HamPack installed. They're marked as dependencies and
# only those nothing else needs are removed, so removing HamPack can't break
# other software. Any kept now go once nothing needs them.
remove_recorded_packages() {
  local recorded=() installed=() orphans=() pkg

  mapfile -t recorded < <(recorded_installs installed-packages)
  for pkg in "${recorded[@]}"; do
    [ "$(pacman -Qq "$pkg" 2> /dev/null)" = "$pkg" ] && installed+=("$pkg")
  done
  if [ ${#installed[@]} -eq 0 ]; then
    echo "No packages to remove."
    return 0
  fi

  sudo pacman -D --asdeps "${installed[@]}" > /dev/null
  while :; do
    mapfile -t orphans < <(comm -12 <(pacman -Qdtq | sort) <(printf '%s\n' "${installed[@]}" | sort))
    [ ${#orphans[@]} -eq 0 ] && break
    echo "Removing packages: ${orphans[*]}"
    sudo pacman -Rns --noconfirm "${orphans[@]}" || break
  done

  local kept=()
  for pkg in "${installed[@]}"; do
    pacman -Qq "$pkg" &> /dev/null && kept+=("$pkg")
  done
  [ ${#kept[@]} -eq 0 ] ||
    echo "Kept because other software needs them: ${kept[*]}"
}

remove_recorded_flatpaks() {
  local recorded=()
  mapfile -t recorded < <(recorded_installs installed-flatpaks)
  [ ${#recorded[@]} -eq 0 ] || remove_flatpaks "${recorded[@]}"
}

# Tell the user about packages and Flatpaks from HamPack's lists that are still
# installed but weren't recorded as installed by HamPack: they were there
# before HamPack, or installed before it kept records, so they're left alone
report_unrecorded() {
  local pkg leftover=() leftover_flatpaks=() coredesktop_pkgs

  coredesktop_pkgs="$(sed -nE 's/^[[:space:]]+([a-z0-9@._+-]+).*/\1/p' "$COREDESKTOP/packages.conf" 2> /dev/null)"
  for pkg in "${UTILITIES[@]}" "${APPLICATIONS[@]}"; do
    [ "$(pacman -Qq "$pkg" 2> /dev/null)" = "$pkg" ] || continue
    grep -qxF "$pkg" <<< "$coredesktop_pkgs" && continue
    leftover+=("$pkg")
  done
  for pkg in "${FLATPAKS[@]}"; do
    flatpak info "$pkg" &> /dev/null && leftover_flatpaks+=("$pkg")
  done

  if [ ${#leftover[@]} -gt 0 ] || [ ${#leftover_flatpaks[@]} -gt 0 ]; then
    echo ""
    echo "These are on HamPack's list but were left in place, because HamPack has no"
    echo "record of installing them (you had them already, or they were installed"
    echo "before HamPack kept records). Remove any you don't need yourself:"
    [ ${#leftover[@]} -eq 0 ] || echo "  sudo pacman -Rns ${leftover[*]}"
    [ ${#leftover_flatpaks[@]} -eq 0 ] || echo "  sudo flatpak uninstall ${leftover_flatpaks[*]}"
  fi
}

# --- Main ---

clear
print_logo

if ! HAMPACK_DIR="$(find_hampack_dir)"; then
  echo "Couldn't find HamPack in ~/.local/share/siblings, so there's nothing to remove."
  echo "If it's installed elsewhere, run its hampackremove from there."
  exit 1
fi
export HAMPACK_DIR
source "$HAMPACK_DIR/lib.sh"
source "$COREDESKTOP/utils.sh"
source "$HAMPACK_DIR/packages.conf"

echo "This will remove HamPack, the applications it installed, and the packages it"
echo "installed that nothing else needs."
echo ""
read -rp "Are you sure you want to continue? [y/N] " confirm
[[ "$confirm" =~ ^[yY] ]] || { echo "Aborted."; exit 0; }
echo ""

start_sudo_keepalive || exit 1

echo "Removing graywolf systemd service..."
remove_graywolf_service

echo "Removing installed applications..."
remove_manifests
parse_conf "$HAMPACK_DIR/binaries.conf" remove_binary_app
parse_conf "$HAMPACK_DIR/compile.conf" remove_compiled_app
remove_unrecorded_build_files
sudo udevadm control --reload-rules

echo "Removing HamPack scripts..."
rm -f "$BIN"/hampackrefresh "$BIN"/hampackupdate "$BIN"/hampackcheck "$BIN"/hampack

echo "Uninstalling not1mm..."
if command -v uv &> /dev/null; then
  uv tool uninstall not1mm 2> /dev/null
fi
rm -f "$APPLICATIONS_DIR/k6gte-not1mm.desktop" "$HOME"/.local/share/icons/hicolor/*/apps/k6gte-not1mm.png

# Before packages, while Wine is still installed
echo "Removing Wine applications..."
remove_wine_apps

echo "Removing Flatpak applications..."
remove_recorded_flatpaks

echo "Removing system packages..."
remove_recorded_packages

echo "Removing desktop files..."
rm -f "$APPLICATIONS_DIR/hampack.desktop" "$HOME"/.local/share/icons/hicolor/*/apps/computer.young.HamPack.png
update-desktop-database "$APPLICATIONS_DIR" 2> /dev/null
update-mime-database "$HOME/.local/share/mime" &> /dev/null

report_unrecorded

echo ""
echo "Removing HamPack state and data..."
rm -rf "$HAMPACK_STATE" "$HOME/.local/share/HamPack"
rm -f "$COREDESKTOP"/updates.d/[0-9][0-9][0-9]-hampack-*
rm -f "$BIN/hampackremove"

# Remove the sibling clone, so CoreDesktop's `update` stops updating HamPack
rm -rf "$HAMPACK_DIR"

echo ""
echo "HamPack has been removed."
