#!/bin/sh
# Remove DevDash from this Mac.
#
#   curl -fsSL https://devdash.pro/uninstall.sh | sh
#   curl -fsSL https://devdash.pro/uninstall.sh | sh -s -- --purge
#
# Stops the service, removes its LaunchAgent and ~/.devdash/bin/devdash.
# Your projects and settings are kept unless --purge is given, which deletes
# them and every project's saved credentials after asking.
set -eu

BIN="$HOME/.devdash/bin/devdash"
PURGE=""
for arg in "$@"; do
  case "$arg" in
    --purge) PURGE="--purge" ;;
    *) printf 'devdash uninstall: unknown option %s\n' "$arg" >&2; exit 2 ;;
  esac
done

if [ -x "$BIN" ]; then
  if [ -n "$PURGE" ] && [ ! -t 0 ] && [ -r /dev/tty ]; then
    # Piped into sh: read the confirmation from the terminal.
    "$BIN" uninstall --purge </dev/tty
  else
    # shellcheck disable=SC2086
    "$BIN" uninstall $PURGE
  fi
else
  # No binary (already removed by hand): undo the LaunchAgents (service and menu bar) ourselves.
  for LABEL in com.dgastudio.devdash com.dgastudio.devdash.menubar; do
    launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
    rm -f "$HOME/Library/LaunchAgents/$LABEL.plist"
  done
  [ -n "$PURGE" ] && printf 'The devdash binary is gone, so --purge cannot remove saved credentials. Delete ~/Library/Application Support/com.dgastudio.devdash8 by hand if you want the data gone.\n'
fi
rmdir "$HOME/.devdash/bin" "$HOME/.devdash" 2>/dev/null || true
printf 'DevDash is uninstalled.\n'
