#!/usr/bin/env bash
# PrivateBackup — Uninstall script
#
# Removes the backend service and deletes installed binaries.
# Does NOT remove configuration or backup data.
#
# Usage:
#   sudo ./uninstall.sh        # remove system-wide install
#   ./uninstall.sh --user      # remove user-level install
#
set -euo pipefail

USER_INSTALL=false
PREFIX="/usr/local"

while [[ $# -gt 0 ]]; do
    case $1 in
        --user)
            USER_INSTALL=true
            PREFIX="$HOME/.local"
            shift ;;
        --prefix)
            PREFIX="$2"
            shift 2 ;;
        -h|--help)
            echo "Usage: $0 [--user] [--prefix DIR]"
            exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

BIN_DIR="$PREFIX/bin"
BACKEND_BIN="$BIN_DIR/privatebackup-backend"

echo "PrivateBackup Uninstaller"
echo "─────────────────────────"
echo ""

# ── Remove service ───────────────────────────────────────────────────────────
if [[ -x "$BACKEND_BIN" ]]; then
    echo "Removing backend service..."
    "$BACKEND_BIN" service uninstall 2>&1 || true
fi

# ── Remove binaries ──────────────────────────────────────────────────────────
for name in privatebackup-backend privatebackup PrivateBackup; do
    target="$BIN_DIR/$name"
    if [[ -f "$target" ]]; then
        rm -f "$target"
        echo "  Removed $target"
    fi
done

# ── Remove shell completions ─────────────────────────────────────────────────
SHARE_DIR="$PREFIX/share"
for path in \
    "$SHARE_DIR/bash-completion/completions/privatebackup" \
    "$SHARE_DIR/zsh/site-functions/_privatebackup" \
    "$SHARE_DIR/fish/vendor_completions.d/privatebackup.fish"; do
    if [[ -f "$path" ]]; then
        rm -f "$path"
        echo "  Removed $path"
    fi
done

echo ""
echo "Uninstall complete."
echo ""
echo "Your configuration and backup data were NOT removed."
echo "To remove those as well, delete:"
echo "  ~/.config/privatebackup/"
echo ""
