#!/bin/bash

# omarchy:summary=Remove the Perplexity desktop app along with its runtime caches.
# omarchy:requires-sudo=true

# -u so an unset HOME is an error rather than a set of rm -rf paths rooted at /.
set -euo pipefail

omarchy-pkg-drop perplexity

# The runtime the app downloads for itself: llama.cpp builds and local models
# under ~/.local/share, the older download location under ~/.cache. Of the
# perplexity-* dirs these are the only ones the desktop app owns; the rest
# belong to Perplexity products that outlive it.
rm -rf \
  "$HOME/.cache/Perplexity" \
  "$HOME/.cache/perplexity-rpc-server" \
  "$HOME/.local/share/perplexity-rpc-server"

# What is left is the user's: the logins and session in ~/.config/Perplexity,
# the secret vault and device identity in ~/.local/state/perplexity, and the
# launcher flags. Keeping them stays the default -- they are small, and being
# signed in after a reinstall is the better surprise -- but a removal meant to
# be complete should not leave credentials behind either, so the choice is put
# in front of the user, default no. Without a terminal to ask in, keeping it
# is the answer -- and gum draws the prompt on stderr, so a redirected stderr
# would block on a question nobody can see.
data_removed=false
if [[ -t 0 && -t 2 ]]; then
  # du answers non-zero when a directory is missing, and pipefail would turn
  # that into an aborted removal; the size is worth no such thing.
  size=$(du -shc "$HOME/.config/Perplexity" "$HOME/.local/state/perplexity" 2>/dev/null | tail -1 | cut -f1 || true)
  if gum confirm --default=false "Also delete your Perplexity data ($size: logins, settings, secret vault and device identity)?"; then
    rm -rf \
      "$HOME/.config/Perplexity" \
      "$HOME/.local/state/perplexity"
    rm -f "$HOME/.config/perplexity-flags.conf"
    data_removed=true
  fi
fi

echo ""
echo "Perplexity has been removed."
if [[ $data_removed == "true" ]]; then
  echo "Its logins, settings, secret vault, and device identity are gone too."
else
  echo "Nothing of yours was touched: not the logins in ~/.config/Perplexity,"
  echo "nor the secret vault and device identity in ~/.local/state/perplexity."
fi
