#!/bin/bash

# NUPST Uninstaller Script
# Completely removes NUPST from the system

# Check if running as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root (sudo ./uninstall.sh)"
  exit 1
fi

echo "NUPST Uninstaller"
echo "================="
echo "This script will completely remove NUPST from your system."

# Find the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

# Step 1: Stop and disable the systemd service if it exists
if [ -f "/etc/systemd/system/nupst.service" ]; then
  echo "Stopping NUPST service..."
  systemctl stop nupst.service 2>/dev/null
  
  echo "Disabling NUPST service..."
  systemctl disable nupst.service 2>/dev/null

  echo "Removing systemd service file..."
  rm -f /etc/systemd/system/nupst.service
  
  echo "Reloading systemd daemon..."
  systemctl daemon-reload
fi

# Step 2: Remove global symlink
if [ -L "/usr/local/bin/nupst" ]; then
  echo "Removing global symlink..."
  rm -f /usr/local/bin/nupst
fi

# Step 3: Ask about removing configuration
read -p "Do you want to remove the NUPST configuration files? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  echo "Removing configuration files..."
  rm -rf /etc/nupst
fi

# Step 4: Check if this was a git installation
if [ -d "$SCRIPT_DIR/.git" ]; then
  echo
  echo "This appears to be a git installation. The local repository will remain intact."
  echo "If you wish to completely remove it, you can delete the directory:"
  echo "  rm -rf $SCRIPT_DIR"
fi

# Check for npm global installation
NODE_PATH=$(which node 2>/dev/null)
if [ -n "$NODE_PATH" ]; then
  NPM_PATH=$(dirname "$NODE_PATH")/npm
  if [ -x "$NPM_PATH" ]; then
    echo
    echo "If you installed NUPST via npm, you may want to uninstall it with:"
    echo "  npm uninstall -g @serve.zone/nupst"
  fi
fi

echo
echo "NUPST has been uninstalled from your system."