#!/bin/bash
# BitBull Monitor — uninstaller
set -euo pipefail

SERVICE_NAME="bitbull-monitor"
INSTALL_DIR="${INSTALL_DIR:-/opt/bitbull-monitor}"
DATA_DIR="${DATA_DIR:-/var/lib/bitbull-monitor}"
ENV_FILE="/etc/bitbull-monitor.env"

if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root: sudo bash uninstall.sh"
  exit 1
fi

read -r -p "Remove BitBull Monitor service and binary? [y/N] " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
  echo "Cancelled."
  exit 0
fi

KEEP_DATA=true
read -r -p "Delete data directory $DATA_DIR? [y/N] " data_confirm
if [ "$data_confirm" = "y" ] || [ "$data_confirm" = "Y" ]; then
  KEEP_DATA=false
fi

if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
  systemctl stop "$SERVICE_NAME"
fi
systemctl disable "$SERVICE_NAME" 2>/dev/null || true
rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
systemctl daemon-reload

rm -rf "$INSTALL_DIR"

if [ "$KEEP_DATA" = false ]; then
  rm -rf "$DATA_DIR"
  rm -f "$ENV_FILE"
  echo "Removed data and config."
else
  echo "Kept data at $DATA_DIR and config at $ENV_FILE"
fi

echo "BitBull Monitor uninstalled."
