#!/bin/bash

# AutoNAS Uninstall Script
# This script is installed on each cluster node for version-specific removal
# Executed by deploy.sh or can be run directly on node: /usr/local/lib/autonas/autonas-uninstall.sh

# Global configuration
LOG_TAG="autonas-uninstall"

set -e  # Exit on any error

# Check for force flag for silent cleanup
FORCE_MODE=false
if [ "$1" = "--force" ]; then
    FORCE_MODE=true
fi

# Helper function for conditional logging
log_message() {
    if [ "$FORCE_MODE" = false ]; then
        echo "$1"
    fi
}

CONFIG_DIR="/etc/pve/autonas"
SCRIPT_NAME="autonas-disk-handler.sh"
WRAPPER_NAME="autonas-udev-wrapper.sh"
BOOT_SCAN_SCRIPT="autonas-boot-scan.sh"
CAMERA_IMPORT_SCRIPT="autonas-media-importer.sh"
INTERFACE_HANDLER_SCRIPT="autonas-network-handler.sh"
UNIFIED_SCRIPT="autonas.sh"
UDEV_RULES="99-autonas-disk.rules"
SYSTEMD_SERVICE="autonas-attach@.service"
MAIN_SERVICE="autonas.service"
BOOT_SCAN_SERVICE="autonas-boot-scan.service"

if [ "$FORCE_MODE" = false ]; then
    echo "=== AutoNAS Uninstall Script ==="
    echo ""
fi

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

log_message "🗑️  Uninstalling AutoNAS..."
log_message ""

# Remove scripts
log_message "Removing AutoNAS scripts..."
if [ -f "/usr/local/bin/$SCRIPT_NAME" ]; then
    rm "/usr/local/bin/$SCRIPT_NAME"
    log_message "✓ Manager script removed"
fi

if [ -f "/usr/local/bin/$WRAPPER_NAME" ]; then
    rm "/usr/local/bin/$WRAPPER_NAME"
    log_message "✓ Wrapper script removed"
fi

if [ -f "/usr/local/bin/$BOOT_SCAN_SCRIPT" ]; then
    rm "/usr/local/bin/$BOOT_SCAN_SCRIPT"
    log_message "✓ Boot scan script removed"
fi

if [ -f "/usr/local/bin/$CAMERA_IMPORT_SCRIPT" ]; then
    rm "/usr/local/bin/$CAMERA_IMPORT_SCRIPT"
    log_message "✓ Camera import script removed"
fi

if [ -f "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT" ]; then
    rm "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT"
    log_message "✓ Interface handler script removed"
fi

if [ -f "/usr/local/bin/$UNIFIED_SCRIPT" ]; then
    rm "/usr/local/bin/$UNIFIED_SCRIPT"
    log_message "✓ Unified AutoNAS script removed"
fi

# Remove symlink
if [ -L "/usr/local/bin/autonas" ]; then
    rm "/usr/local/bin/autonas"
    log_message "✓ AutoNAS symlink removed"
fi

# Remove internal scripts directory
if [ -d "/usr/local/lib/autonas" ]; then
    rm -rf "/usr/local/lib/autonas"
    log_message "✓ AutoNAS internal scripts directory removed"
fi

# Aggressive cleanup for orphaned files from previous versions
log_message "Cleaning up orphaned files from previous versions..."
for orphan_file in "autonas-interface-debug.sh" "autonas-test-interface-stability.sh"; do
    if [ -f "/usr/local/bin/$orphan_file" ]; then
        rm "/usr/local/bin/$orphan_file"
        log_message "✓ Orphaned file removed: $orphan_file"
    fi
done

# Remove udev rules
log_message "Removing udev rules..."
if [ -f "/etc/udev/rules.d/$UDEV_RULES" ]; then
    rm "/etc/udev/rules.d/$UDEV_RULES"
    udevadm control --reload-rules
    log_message "✓ Udev rules removed"
fi

# Remove systemd service
log_message "Removing systemd service..."
if [ -f "/etc/systemd/system/$SYSTEMD_SERVICE" ]; then
    systemctl stop autonas-attach@*.service 2>/dev/null || true
    systemctl disable autonas-attach@*.service 2>/dev/null || true
    rm "/etc/systemd/system/$SYSTEMD_SERVICE"
    systemctl daemon-reload
    log_message "✓ Systemd service removed"
fi

# Remove main service
log_message "Removing main AutoNAS service..."
if [ -f "/etc/systemd/system/$MAIN_SERVICE" ]; then
    systemctl stop autonas.service 2>/dev/null || true
    systemctl disable autonas.service 2>/dev/null || true
    rm "/etc/systemd/system/$MAIN_SERVICE"
    systemctl daemon-reload
    log_message "✓ Main AutoNAS service removed"
fi

# Remove boot scan service
log_message "Removing boot scan service..."
if [ -f "/etc/systemd/system/$BOOT_SCAN_SERVICE" ]; then
    systemctl stop autonas-boot-scan.service 2>/dev/null || true
    systemctl disable autonas-boot-scan.service 2>/dev/null || true
    rm "/etc/systemd/system/$BOOT_SCAN_SERVICE"
    systemctl daemon-reload
    log_message "✓ Boot scan service removed"
fi

# Handle configuration and data preservation
log_message ""
log_message "📁 Handling user data..."

# Check if configuration exists and has user data
if [ -f "$CONFIG_DIR/disks.conf" ]; then
    if grep -v '^#' "$CONFIG_DIR/disks.conf" | grep -v '^$' | grep -q ':'; then
        log_message "⚠️  User configurations detected in $CONFIG_DIR/disks.conf"
        log_message "   Configuration file preserved for manual cleanup"
        log_message "   Remove manually with: sudo rm -rf $CONFIG_DIR"
    else
        log_message "ℹ️  Configuration file contains only template - removing"
        rm "$CONFIG_DIR/disks.conf"
        rmdir "$CONFIG_DIR" 2>/dev/null || true
    fi
else
    log_message "ℹ️  No configuration file found"
    rmdir "$CONFIG_DIR" 2>/dev/null || true
fi

# Check for mounted AutoNAS disks
log_message ""
log_message "💾 Checking for mounted AutoNAS disks..."
mounted_autonas=$(mount | grep "/mnt/autonas/" | wc -l)
if [ $mounted_autonas -gt 0 ]; then
    log_message "⚠️  Found $mounted_autonas mounted AutoNAS disk(s):"
    if [ "$FORCE_MODE" = false ]; then
        mount | grep "/mnt/autonas/" | while read line; do
            echo "   $line"
        done
    fi
    log_message ""
    log_message "   These disks are still mounted and in use."
    log_message "   Mount points preserved: /mnt/autonas/"
    log_message "   Unmount manually if needed: sudo umount /mnt/autonas/*"
else
    log_message "ℹ️  No AutoNAS disks currently mounted"
    if [ -d "/mnt/autonas" ]; then
        # Only remove if empty
        if [ -z "$(ls -A /mnt/autonas)" ]; then
            rmdir "/mnt/autonas"
            log_message "✓ Empty AutoNAS mount directory removed"
        else
            log_message "⚠️  AutoNAS mount directory contains files - preserved"
        fi
    fi
fi

# Check NFS exports
log_message ""
log_message "🌐 Checking NFS exports..."
if [ -f "/etc/exports" ] && grep -q "/mnt/autonas/" "/etc/exports" 2>/dev/null; then
    log_message "⚠️  AutoNAS NFS exports found in /etc/exports"
    log_message "   Please manually remove AutoNAS entries from /etc/exports"
    log_message "   And reload NFS exports: sudo exportfs -ra"
else
    log_message "ℹ️  No AutoNAS NFS exports found"
fi

log_message ""
log_message "🎉 AutoNAS core components removed successfully!"

if [ "$FORCE_MODE" = false ]; then
    echo ""
    echo "📋 Summary:"
    echo "✓ Scripts removed from /usr/local/bin/"
    echo "✓ Udev rules removed"
    echo "✓ Systemd services removed"
    echo ""
    echo "⚠️  Preserved (manual cleanup required if desired):"
    echo "• User configurations: $CONFIG_DIR/ (if contains user data)"
    echo "• Mount points: /mnt/autonas/ (if contains data)"
    echo "• NFS exports: /etc/exports (manual edit required)"
    echo ""
    echo "📝 To completely remove all AutoNAS data:"
    echo "sudo rm -rf $CONFIG_DIR"
    echo "sudo rm -rf /mnt/autonas"
    echo "sudo nano /etc/exports  # Remove AutoNAS entries manually"
    echo "sudo exportfs -ra"
fi
echo ""
echo "🔄 To reinstall AutoNAS later, run: sudo bash scripts/install.sh"