#!/bin/bash

# autoSMART Uninstaller
# Version: 1.0
# Description: Complete removal of autoSMART system to prevent orphaned files

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="/opt/autoSMART"
CONFIG_DIR="/etc/autosmart"
PVE_CONFIG_DIR="/etc/pve/autoSMART"
SERVICE_NAME="autosmart"
LOG_DIR="/var/log/autosmart"
SYSTEMD_SERVICE="/etc/systemd/system/${SERVICE_NAME}.service"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_info "🗑️  autoSMART Uninstaller v1.0"
log_info "==============================="

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   log_error "This script must be run as root (use sudo)"
   exit 1
fi

# Stop and disable systemd service
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    log_info "Stopping autoSMART service..."
    systemctl stop "$SERVICE_NAME"
    log_success "Service stopped"
else
    log_info "Service is not running"
fi

if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
    log_info "Disabling autoSMART service..."
    systemctl disable "$SERVICE_NAME"
    log_success "Service disabled"
fi

# Remove systemd service file
if [[ -f "$SYSTEMD_SERVICE" ]]; then
    log_info "Removing systemd service file..."
    rm -f "$SYSTEMD_SERVICE"
    systemctl daemon-reload
    log_success "Service file removed"
fi

# Remove installation directory
if [[ -d "$INSTALL_DIR" ]]; then
    log_info "Removing installation directory: $INSTALL_DIR"
    rm -rf "$INSTALL_DIR"
    log_success "Installation directory removed"
else
    log_info "Installation directory does not exist"
fi

# Remove configuration directory
if [[ -d "$CONFIG_DIR" ]]; then
    log_info "Removing configuration directory: $CONFIG_DIR"
    rm -rf "$CONFIG_DIR"
    log_success "Configuration directory removed"
else
    log_info "Configuration directory does not exist"
fi

# Remove PVE configuration directory (if exists)
if [[ -d "$PVE_CONFIG_DIR" ]]; then
    log_info "Removing PVE configuration directory: $PVE_CONFIG_DIR"
    rm -rf "$PVE_CONFIG_DIR"
    log_success "PVE configuration directory removed"
fi

# Remove log directory
if [[ -d "$LOG_DIR" ]]; then
    log_info "Removing log directory: $LOG_DIR"
    rm -rf "$LOG_DIR"
    log_success "Log directory removed"
fi

# Remove cron jobs (if any)
if crontab -l 2>/dev/null | grep -q "autosmart"; then
    log_info "Removing autoSMART cron jobs..."
    (crontab -l 2>/dev/null | grep -v "autosmart") | crontab -
    log_success "Cron jobs removed"
fi

# Remove temporary files
TEMP_FILES=(
    "/tmp/autosmart*"
    "/tmp/smart-*"
    "/var/tmp/autosmart*"
)

for pattern in "${TEMP_FILES[@]}"; do
    if ls $pattern 1> /dev/null 2>&1; then
        log_info "Removing temporary files: $pattern"
        rm -rf $pattern
    fi
done

# Remove user and group (if created specifically for autoSMART)
if id "autosmart" &>/dev/null; then
    log_warning "Found autosmart user - leaving intact (may be used by database)"
    log_info "To remove user manually: userdel autosmart"
fi

# Clean up any remaining processes
PROCESSES=$(pgrep -f "autosmart|smart-collector" || true)
if [[ -n "$PROCESSES" ]]; then
    log_warning "Found running autoSMART processes: $PROCESSES"
    log_info "Terminating processes..."
    pkill -f "autosmart|smart-collector" || true
    sleep 2
    pkill -9 -f "autosmart|smart-collector" || true
    log_success "Processes terminated"
fi

# Remove from PATH modifications (if any)
PROFILE_FILES=(
    "/etc/profile.d/autosmart.sh"
    "/etc/bash.bashrc.d/autosmart.sh"
)

for file in "${PROFILE_FILES[@]}"; do
    if [[ -f "$file" ]]; then
        log_info "Removing PATH modification: $file"
        rm -f "$file"
    fi
done

# Clean package manager cache related to autoSMART dependencies
log_info "Cleaning package cache..."
if command -v apt-get &> /dev/null; then
    apt-get clean >/dev/null 2>&1 || true
elif command -v yum &> /dev/null; then
    yum clean all >/dev/null 2>&1 || true
fi

# Final verification
REMAINING_FILES=$(find /etc /opt /var -name "*autosmart*" -o -name "*autoSMART*" 2>/dev/null | head -10)
if [[ -n "$REMAINING_FILES" ]]; then
    log_warning "Some autoSMART files may still exist:"
    echo "$REMAINING_FILES"
    log_info "These may be database files or manually created configurations"
fi

log_success "✅ autoSMART uninstallation complete!"
log_info ""
log_info "📋 Summary of removed components:"
log_info "  • Systemd service: $SERVICE_NAME"
log_info "  • Installation directory: $INSTALL_DIR"
log_info "  • Configuration directory: $CONFIG_DIR"
log_info "  • Log directory: $LOG_DIR"
log_info "  • Temporary files and processes"
log_info ""
log_info "💡 Notes:"
log_info "  • Database data is preserved (not removed)"
log_info "  • System packages (Perl, PostgreSQL client) are preserved"
log_info "  • User 'autosmart' is preserved if it exists"
log_info ""
log_info "🔄 System is now clean and ready for fresh installation"

exit 0
