#!/bin/bash

# AutoNAS Installation & Node Admin Script
# Executed on target nodes; deploy.sh invokes this with subcommands.
# Usage: install.sh [install|start|restart|stop|status]

set -e  # Exit on any error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
CONFIG_DIR="/etc/pve/autonas"

# Script names
UNIFIED_SCRIPT="autonas.sh"
SCRIPT_NAME="autonas-disk-handler.sh"
WRAPPER_NAME="autonas-udev-wrapper.sh"
BOOT_SCAN_SCRIPT="autonas-boot-scan.sh"
INTERFACE_HANDLER_SCRIPT="autonas-network-handler.sh"
CAMERA_IMPORT_SCRIPT="autonas-media-importer.sh"
UDEV_RULES="99-autonas-disk.rules"
INTERFACE_RULES="98-autonas-interfaces.rules"
SYSTEMD_SERVICE="autonas-attach@.service"
MAIN_SERVICE="autonas.service"
BOOT_SCAN_SERVICE="autonas-boot-scan.service"

require_root() {
    if [ "$EUID" -ne 0 ]; then
        echo "❌ This action must be run as root (use sudo)" >&2
        exit 1
    fi
}

# Verifică dacă un pachet este instalat
is_package_installed() {
    local package="$1"
    dpkg -l "$package" 2>/dev/null | grep -q "^ii"
}

# Verifică dependințele necesare
check_dependencies() {
    local missing_packages=()
    local required_packages=("nfs-kernel-server" "autofs" "udev" "libimage-exiftool-perl")
    
    echo "🔍 Verificare dependințe AutoNAS..."
    
    for package in "${required_packages[@]}"; do
        if is_package_installed "$package"; then
            echo "✓ $package - instalat"
        else
            echo "❌ $package - LIPSĂ"
            missing_packages+=("$package")
        fi
    done
    
    if [ ${#missing_packages[@]} -gt 0 ]; then
        echo ""
        echo "⚠️  DEPENDINȚE LIPSĂ DETECTATE:"
        printf "   %s\n" "${missing_packages[@]}"
        echo ""
        echo "Pentru a instala dependințele lipsă, rulați:"
        echo "   apt update && apt install -y ${missing_packages[*]}"
        echo ""
        echo "Sau utilizați comanda 'install-deps' pentru instalare automată:"
        echo "   $0 install-deps"
        echo ""
        return 1
    else
        echo "✅ Toate dependințele sunt instalate"
        return 0
    fi
}

# Instalează doar dependințele lipsă
install_dependencies() {
    require_root
    echo "📦 Instalare dependințe AutoNAS..."
    
    if ! command -v apt >/dev/null 2>&1; then
        echo "❌ Sistemul nu folosește apt - instalarea automată nu este suportată"
        echo "Instalați manual pachetele: nfs-kernel-server autofs udev libimage-exiftool-perl"
        exit 1
    fi
    
    echo "Actualizare lista de pachete..."
    if ! apt update; then
        echo "❌ Nu s-a putut actualiza lista de pachete - verificați conectivitatea la internet"
        exit 1
    fi
    
    echo "Instalare pachete necesare..."
    if apt install -y nfs-kernel-server autofs udev libimage-exiftool-perl; then
        echo "✅ Dependințele au fost instalate cu succes"
    else
        echo "❌ Eroare la instalarea dependințelor"
        exit 1
    fi
}

do_start() {
    require_root
    echo "Starting AutoNAS services..."
    systemctl enable nfs-kernel-server >/dev/null 2>&1 || true
    systemctl start nfs-kernel-server || true
    udevadm control --reload-rules || true
    udevadm trigger --subsystem-match=block --action=add || true
    echo "✓ Start complete"
}

do_restart() {
    require_root
    echo "Restarting AutoNAS services..."
    systemctl restart nfs-kernel-server || true
    udevadm control --reload-rules || true
    udevadm trigger --subsystem-match=block --action=add || true
    echo "✓ Restart complete"
}

do_stop() {
    require_root
    echo "Stopping AutoNAS services..."
    systemctl stop nfs-kernel-server || true
    echo "✓ Stop complete"
}

do_status() {
    echo "=== Status Servicii ==="
    systemctl status nfs-kernel-server --no-pager -l || true
    echo ""
    echo "=== Exports NFS ==="
    cat /etc/exports 2>/dev/null || echo "Fișier /etc/exports nu există"
    echo ""
    echo "=== Mount Points AutoNAS ==="
    ls -la /mnt/autonas/ 2>/dev/null || echo "Director /mnt/autonas nu există"
    echo ""
    echo "=== Configurație Diskuri ==="
    cat "$CONFIG_DIR/disks.conf" 2>/dev/null || echo "Fișier configurație nu există"
    echo ""
    echo "=== Procese AutoNAS ==="
    ps aux | grep autonas | grep -v grep || true
}

do_install() {
    require_root
    echo "=== AutoNAS Installation Script ==="
    echo ""
    
    # Verifică dependințele mai întâi
    if ! check_dependencies; then
        echo "❌ Instalarea nu poate continua - dependințe lipsă"
        echo "Rulați mai întâi: $0 install-deps"
        exit 1
    fi
    
    echo ""
    echo "Installing AutoNAS..."

    echo "🧹 Cleanup previous installation to prevent orphan files..."
    if [ -f "/usr/local/lib/autonas/autonas-uninstall.sh" ]; then
        echo "Previous AutoNAS installation detected. Running uninstall first..."
        bash /usr/local/lib/autonas/autonas-uninstall.sh --force >/dev/null 2>&1 || true
        echo "Previous installation cleaned up."
    fi

    echo "📁 Creating directories..."
    mkdir -p "$CONFIG_DIR"
    mkdir -p "/mnt/autonas"
    echo "✓ Directories created"

    echo "Installing AutoNAS scripts..."
    mkdir -p "/usr/local/lib/autonas"

    if [ -f "$SCRIPT_DIR/$UNIFIED_SCRIPT" ]; then
        cp "$SCRIPT_DIR/$UNIFIED_SCRIPT" "/usr/local/bin/"
        chmod +x "/usr/local/bin/$UNIFIED_SCRIPT"
        echo "✓ Unified AutoNAS script installed"
        ln -sf "/usr/local/bin/$UNIFIED_SCRIPT" "/usr/local/bin/autonas"
        echo "✓ Created 'autonas' command symlink"
    fi

    if [ -f "$SCRIPT_DIR/autonas-core.sh" ]; then
        cp "$SCRIPT_DIR/autonas-core.sh" "/usr/local/bin/"
        chmod +x "/usr/local/bin/autonas-core.sh"
        echo "✓ Core library installed"
    fi

    cp "$SCRIPT_DIR/$SCRIPT_NAME" "/usr/local/bin/"
    chmod +x "/usr/local/bin/$SCRIPT_NAME"
    echo "✓ autonas-disk-handler.sh installed"

    cp "$SCRIPT_DIR/$WRAPPER_NAME" "/usr/local/bin/"
    chmod +x "/usr/local/bin/$WRAPPER_NAME"
    echo "✓ autonas-udev-wrapper.sh installed"

    if [ -f "$SCRIPT_DIR/$BOOT_SCAN_SCRIPT" ]; then
        cp "$SCRIPT_DIR/$BOOT_SCAN_SCRIPT" "/usr/local/bin/"
        chmod +x "/usr/local/bin/$BOOT_SCAN_SCRIPT"
        echo "✓ Boot scan script installed"
    fi

    if [ -f "$SCRIPT_DIR/$INTERFACE_HANDLER_SCRIPT" ]; then
        cp "$SCRIPT_DIR/$INTERFACE_HANDLER_SCRIPT" "/usr/local/bin/"
        chmod +x "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT"
        echo "✓ Interface handler script installed"
    fi

    if [ -f "$SCRIPT_DIR/$CAMERA_IMPORT_SCRIPT" ]; then
        cp "$SCRIPT_DIR/$CAMERA_IMPORT_SCRIPT" "/usr/local/bin/"
        chmod +x "/usr/local/bin/$CAMERA_IMPORT_SCRIPT"
        echo "✓ Camera import script installed"
    fi

    echo "Installing udev rules..."
    cp "$PROJECT_DIR/config/$UDEV_RULES" "/etc/udev/rules.d/"
    if [ -f "$PROJECT_DIR/config/$INTERFACE_RULES" ]; then
        cp "$PROJECT_DIR/config/$INTERFACE_RULES" "/etc/udev/rules.d/"
        echo "✓ Interface monitoring udev rules installed"
    fi
    udevadm control --reload-rules
    echo "✓ Udev rules installed"

    echo "Installing systemd services..."
    cp "$PROJECT_DIR/config/$SYSTEMD_SERVICE" "/etc/systemd/system/"
    systemctl daemon-reload
    echo "✓ Systemd service installed"

    echo "Installing main AutoNAS service..."
    cp "$PROJECT_DIR/config/$MAIN_SERVICE" "/etc/systemd/system/"
    systemctl daemon-reload
    systemctl enable autonas.service
    echo "✓ Main AutoNAS service installed and enabled"

    echo "Installing boot scan service..."
    cp "$PROJECT_DIR/config/$BOOT_SCAN_SERVICE" "/etc/systemd/system/"
    systemctl daemon-reload
    systemctl enable autonas-boot-scan.service
    echo "✓ Boot scan service installed and enabled"

    echo "Setting up configuration..."
    if [ ! -f "$CONFIG_DIR/disks.conf" ]; then
        cp "$PROJECT_DIR/config/disks.conf" "$CONFIG_DIR/"
        echo "✓ Configuration template installed"
    else
        echo "⚠️  Configuration file already exists, preserving user settings"
        echo "   Existing file: $CONFIG_DIR/disks.conf"
        echo "   Template available at: $PROJECT_DIR/config/disks.conf"
        if grep -v '^#' "$CONFIG_DIR/disks.conf" | grep -v '^$' | grep -q ':'; then
            echo "✓ User configurations detected in existing file - preserving"
        else
            echo "ℹ️  Existing file appears to be template only"
        fi
    fi

    echo "Starting services..."
    systemctl enable nfs-kernel-server
    systemctl start nfs-kernel-server
    if [ ! -f /etc/exports ]; then
        touch /etc/exports
    fi

    echo "🔐 Setting permissions..."
    if [ -f "/usr/local/bin/$UNIFIED_SCRIPT" ]; then
        chown root:root "/usr/local/bin/$UNIFIED_SCRIPT"
        chmod 755 "/usr/local/bin/$UNIFIED_SCRIPT"
    fi
    chown root:root "/usr/local/bin/$SCRIPT_NAME"
    chown root:root "/usr/local/bin/$WRAPPER_NAME"
    if [ -f "/usr/local/bin/$CONFIG_SCRIPT" ]; then
        chown root:root "/usr/local/bin/$CONFIG_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$BOOT_SCAN_SCRIPT" ]; then
        chown root:root "/usr/local/bin/$BOOT_SCAN_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT" ]; then
        chown root:root "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT" ]; then
        chown root:root "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT"
    fi
    chmod 755 "/usr/local/bin/$SCRIPT_NAME"
    chmod 755 "/usr/local/bin/$WRAPPER_NAME"
    if [ -f "/usr/local/bin/$UNIFIED_SCRIPT" ]; then
        chmod 755 "/usr/local/bin/$UNIFIED_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$CONFIG_SCRIPT" ]; then
        chmod 755 "/usr/local/bin/$CONFIG_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$BOOT_SCAN_SCRIPT" ]; then
        chmod 755 "/usr/local/bin/$BOOT_SCAN_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT" ]; then
        chmod 755 "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT"
    fi
    if [ -f "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT" ]; then
        chmod 755 "/usr/local/bin/$INTERFACE_HANDLER_SCRIPT"
    fi
    echo "✓ Permissions set"

    echo "📁 Verifying installation..."
    [ -f "/usr/local/bin/$SCRIPT_NAME" ] && echo "✓ Manager script: /usr/local/bin/$SCRIPT_NAME"
    [ -f "/usr/local/bin/$WRAPPER_NAME" ] && echo "✓ Wrapper script: /usr/local/bin/$WRAPPER_NAME"
    [ -f "/usr/local/bin/$UNIFIED_SCRIPT" ] && echo "✓ Unified script: /usr/local/bin/$UNIFIED_SCRIPT"
    [ -f "/usr/local/bin/$CONFIG_SCRIPT" ] && echo "✓ Configuration script: /usr/local/bin/$CONFIG_SCRIPT"
    [ -f "/usr/local/bin/$BOOT_SCAN_SCRIPT" ] && echo "✓ Boot scan script: /usr/local/bin/$BOOT_SCAN_SCRIPT"
    [ -f "/etc/udev/rules.d/$UDEV_RULES" ] && echo "✓ Udev rules: /etc/udev/rules.d/$UDEV_RULES"
    [ -f "/etc/systemd/system/$SYSTEMD_SERVICE" ] && echo "✓ Systemd service: /etc/systemd/system/$SYSTEMD_SERVICE"
    [ -f "/etc/systemd/system/$MAIN_SERVICE" ] && echo "✓ Main AutoNAS service: /etc/systemd/system/$MAIN_SERVICE"
    [ -f "/etc/systemd/system/$BOOT_SCAN_SERVICE" ] && echo "✓ Boot scan service: /etc/systemd/system/$BOOT_SCAN_SERVICE"
    [ -f "$CONFIG_DIR/disks.conf" ] && echo "✓ Configuration file: $CONFIG_DIR/disks.conf"

    echo "Installing uninstall script for future upgrades..."
    if [ -f "$SCRIPT_DIR/autonas-uninstall.sh" ]; then
        cp "$SCRIPT_DIR/autonas-uninstall.sh" "/usr/local/lib/autonas/autonas-uninstall.sh"
        chmod +x "/usr/local/lib/autonas/autonas-uninstall.sh"
        chown root:root "/usr/local/lib/autonas/autonas-uninstall.sh"
        echo "✓ Uninstall script: /usr/local/lib/autonas/autonas-uninstall.sh"
    else
        echo "⚠️  Uninstall script not found - manual cleanup may be required for future reinstalls"
    fi

    echo ""
    echo "🎉 AutoNAS installation completed successfully!"
    echo ""
    echo "🔄 Starting services..."
    if [ -n "${INTERFACE_MONITOR_SCRIPT:-}" ] && [ -f "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT" ]; then
        echo "🔄 Running initial interface IP restore..."
        "/usr/local/bin/$INTERFACE_MONITOR_SCRIPT" restore || true
        echo "✓ Initial interface restore completed"
    fi

    echo ""
    echo "📝 Next steps:"
    echo "1. Connect your external disks to test auto-detection"
    echo "2. Use 'autonas add <UUID>' to configure detected disks"
    echo "3. Monitor with: journalctl -t autonas -t autonas-wrapper -f"
    echo ""
    echo "🔧 Configuration commands:"
    echo "  autonas add [UUID]     - Add new disk configuration"
    echo "  autonas list           - List configured disks"
    echo "  autonas test [UUID]    - Test disk configuration"
    echo "  autonas remove         - Remove disk configuration"
    echo ""
    echo "📋 Example disk configuration:"
    echo "12345678-1234-1234-1234-123456789abc:storage1:192.168.1.100:eth0:/mnt/autonas/storage1:*(rw,all_squash,insecure,async,no_subtree_check,anonuid=0,anongid=0)"
    echo ""
    echo "✅ AutoNAS is ready to use!"
    echo "🔍 Interface monitoring is handled automatically by udev events"
}

cmd="${1:-install}"
case "$cmd" in
    install)
        do_install
        ;;
    install-deps)
        install_dependencies
        ;;
    check-deps)
        check_dependencies
        ;;
    start)
        do_start
        ;;
    restart)
        do_restart
        ;;
    stop)
        do_stop
        ;;
    status)
        do_status
        ;;
    *)
        echo "Usage: $0 [install|install-deps|check-deps|start|restart|stop|status]" >&2
        echo ""
        echo "Commands:"
        echo "  install     - Install AutoNAS (requires dependencies)"
        echo "  install-deps- Install only the required dependencies"
        echo "  check-deps  - Check if dependencies are installed"
        echo "  start       - Start AutoNAS services"
        echo "  restart     - Restart AutoNAS services"
        echo "  stop        - Stop AutoNAS services"
        echo "  status      - Show AutoNAS status"
        exit 2
        ;;
esac