#!/bin/bash

# Global Configuration
VERSION="1.0.1"
CONFIG_DIR="/etc/mynas"
LOG_DIR="/var/log/mynas"
BACKUP_DIR="/mnt/backups"
TEMP_DIR="/tmp/mynas"

# Distribution Detection
detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        DISTRO_VERSION=$VERSION_ID
    elif type lsb_release >/dev/null 2>&1; then
        DISTRO=$(lsb_release -si | tr '[:upper:]' '[:lower:]')
        DISTRO_VERSION=$(lsb_release -sr)
    else
        log "ERROR: Could not detect Linux distribution!"
        exit 1
    fi

    case $DISTRO in
        debian|ubuntu)
            PKG_MANAGER="apt"
            INSTALL_CMD="apt install -y --no-install-recommends"
            UPDATE_CMD="apt update && apt upgrade -y"
            NFS_SERVICE="nfs-kernel-server"
            FIREWALL_TYPE="firewalld"
            ;;
        opensuse*|suse)
            PKG_MANAGER="zypper"
            INSTALL_CMD="zypper install -y"
            UPDATE_CMD="zypper refresh && zypper update -y"
            NFS_SERVICE="nfs-server"
            FIREWALL_TYPE="firewalld"
            ;;
        *)
            log "ERROR: Unsupported distribution: $DISTRO"
            exit 1
            ;;
    esac

    log "Detected distribution: $DISTRO $DISTRO_VERSION"
    log "Using firewall type: $FIREWALL_TYPE"
}

# Initialize directories and logging
init() {
    mkdir -p "$CONFIG_DIR" "$LOG_DIR" "$BACKUP_DIR" "$TEMP_DIR"
    local timestamp=$(date +"%Y%m%d_%H%M%S")
    LOG_FILE="$LOG_DIR/mynas_$timestamp.log"
    exec 3>&1 4>&2
    exec > >(tee -a "$LOG_FILE") 2>&1
    
    detect_distro
}

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $@" | tee -a "$LOG_FILE"
}

# Error handling
die() {
    log "ERROR: $@"
    exit 1
}

# Backup configuration file
backup_file() {
    local f="$1"
    if [[ -f "$f" ]] && [[ ! -f "${f}.bak" ]]; then
        cp -a "$f" "${f}.bak"
        log "Backed up $f to ${f}.bak"
    fi
}

# Show help information
show_help() {
    echo "Enterprise NAS Management Tool v$VERSION"
    echo "Usage: mynas [GLOBAL_OPTIONS] -- [MODULE] -- [ACTION] [OPTIONS]"
    echo ""
    echo "Global Options:"
    echo "  --help, -h     Show this help message"
    echo "  --version, -v  Show version information"
    echo "  --verbose      Enable verbose output"
    echo "  --monitor      Enable monitoring features"
    echo "  --disk-health  Check disk health"
    echo ""
    echo "Modules:"
    echo "  --backup       Backup management"
    echo "  --av           Antivirus management (clamav, maldet, rkhunter, chkrootkit)"
    echo "  --system       System management"
    echo "  --monitor      Monitoring management"
    echo "  --storage      Storage management"
    echo "  --nfs          NFS management"
    echo "  --samba        Samba management"
    echo "  --sshfs        SSHFS management"
    echo "  --firewall     Firewall management (firewalld)"
    echo "  --fail2ban     Fail2ban management"
    echo "  --raid         RAID management"
    echo "  --network      Network management"
    echo "  --service      Service management"
    echo "  --user         User management"
    echo ""
    echo "Run 'mynas --help --[MODULE]' for module-specific help"
    echo "All operations are logged to $LOG_DIR"
}

# Module-specific help
module_help() {
    local module="$1"
    case "$module" in
        backup)
            echo "Backup Module Commands:"
            echo "  --tar <source> [dest]          Create tar backup"
            echo "  --zip <source> [dest]          Create zip backup"
            echo "  --dd <source> [dest]           Create disk clone"
            ;;
        av)
            echo "Antivirus Module Commands:"
            echo "  --clamav <path>                Run ClamAV scan"
            echo "  --maldet <path>                Run Maldet scan"
            echo "  --rkhunter                     Run Rootkit Hunter scan"
            echo "  --chkrootkit                   Run chkrootkit scan"
            echo "  --update-databases             Update all AV databases"
            echo "  --clamav-schedule <path>       Schedule weekly ClamAV scan"
            echo "  --maldet-monitor <path>        Enable Maldet monitoring"
            ;;
        system)
            echo "System Module Commands:"
            echo "  --update                       Update system packages"
            ;;
        monitor)
            echo "Monitor Module Commands:"
            echo "  --iostat [interval] [count]    Run iostat monitoring"
            echo "  --netdata <start|stop|restart|status>  Manage netdata service"
            echo "  --disk-health                  Check disk health with SMART"
            ;;
        storage)
            echo "Storage Module Commands:"
            echo "  --list                         List storage devices"
            echo "  --format <device> [fstype]     Format device (default: ext4)"
            echo "  --mount <device> <mountpoint>  Mount device"
            echo "  --umount <mountpoint>          Unmount device"
            echo "  --info <device>                Show device information"
            ;;
        nfs)
            echo "NFS Module Commands:"
            echo "  --install                      Install NFS server"
            echo "  --add-share <path> <clients> [options]  Add NFS share"
            ;;
        samba)
            echo "Samba Module Commands:"
            echo "  --install                      Install Samba"
            echo "  --add-share <name> <path> <users> [writable]  Add Samba share"
            ;;
        sshfs)
            echo "SSHFS Module Commands:"
            echo "  --install                      Install SSHFS"
            echo "  --mount <user> <host> <remote_path> <local_path>  Mount SSHFS"
            ;;
        firewall)
            echo "Firewall Module Commands:"
            echo "  --add-port <port> [proto]      Add port to firewall"
            echo "  --remove-port <port> [proto]   Remove port from firewall"
            echo "  --add-service <service>         Add service to firewall"
            echo "  --remove-service <service>      Remove service from firewall"
            echo "  --list                         List firewall configuration"
            ;;
        fail2ban)
            echo "Fail2ban Module Commands:"
            echo "  --install                      Install fail2ban"
            echo "  --enable-jail <jail>           Enable fail2ban jail"
            echo "  --disable-jail <jail>          Disable fail2ban jail"
            echo "  --status                       Show fail2ban status"
            ;;
        raid)
            echo "RAID Module Commands:"
            echo "  --create <level> <devices> [name]  Create RAID array"
            echo "  --add <array> <device>          Add device to RAID array"
            echo "  --remove <array> <device>       Remove device from RAID array"
            echo "  --stop <array>                  Stop RAID array"
            echo "  --status                        Show RAID status"
            echo "  --save                          Save RAID configuration"
            ;;
        network)
            echo "Network Module Commands:"
            echo "  --list-interfaces              List network interfaces"
            echo "  --set-ip <iface> <ip> [netmask]  Set IP address"
            echo "  --set-gateway <gw>             Set default gateway"
            echo "  --set-dns <dns>                Set DNS server"
            echo "  --test                         Test network connectivity"
            echo "  --bridge <name> <ifaces>       Create network bridge"
            echo "  --bond <name> <mode> <ifaces>  Create network bond"
            ;;
        service)
            echo "Service Module Commands:"
            echo "  --start <service>              Start service"
            echo "  --stop <service>               Stop service"
            echo "  --restart <service>            Restart service"
            echo "  --enable <service>             Enable service"
            echo "  --disable <service>            Disable service"
            echo "  --status <service>             Show service status"
            echo "  --mask <service>               Mask service"
            echo "  --unmask <service>             Unmask service"
            ;;
        user)
            echo "User Module Commands:"
            echo "  --add <user> [shell]           Add user"
            echo "  --remove <user>                Remove user"
            echo "  --list                         List users"
            echo "  --passwd <user>                Change user password"
            echo "  --add-to-group <user> <group>  Add user to group"
            echo "  --remove-from-group <user> <group>  Remove user from group"
            echo "  --list-groups <user>           List user groups"
            echo "  --lock <user>                  Lock user account"
            echo "  --unlock <user>                Unlock user account"
            ;;
        *)
            show_help
            ;;
    esac
}

# ==================== MONITORING FUNCTIONS ====================

monitor_iostat() {
    local interval=${1:-2}
    local count=${2:-5}
    
    if ! command -v iostat &> /dev/null; then
        log "Installing sysstat package for iostat..."
        eval $INSTALL_CMD sysstat
    fi
    
    log "Running iostat (Interval: ${interval}s, Count: ${count})"
    iostat -dxm $interval $count
}

monitor_netdata() {
    NETDATA_PORT=19999

    get_ip() {
        hostname -I | awk '{print $1}'
    }

    case "$1" in
        start|stop|restart|status)
            systemctl "$1" netdata
            if [ "$1" = "start" ]; then
                IP=$(get_ip)
                log "Netdata started at: http://${IP}:${NETDATA_PORT}"
            fi
            ;;
        *)
            die "Invalid netdata command: $1"
            ;;
    esac
}

check_disk_health() {
    log "Checking disk health with SMART..."
    
    if ! command -v smartctl &> /dev/null; then
        log "Installing smartmontools..."
        eval $INSTALL_CMD smartmontools
    fi
    
    for disk in $(lsblk -d -o NAME -n | grep -v loop); do
        local device="/dev/$disk"
        log "Checking health of $device"
        smartctl -H $device || die "Failed to check disk health"
        smartctl -A $device | grep -E "^  5|^196|^197|^198" || true
    done
}

# ==================== BACKUP FUNCTIONS ====================

backup_tar() {
    local source="$1"
    local dest="${2:-$BACKUP_DIR/backup_$(date +%Y%m%d).tar.gz}"
    log "Creating tar backup of $source to $dest"
    sudo tar -czvf "$dest" "$source" || die "Failed to create tar backup"
    log "Backup completed successfully. Size: $(du -h "$dest" | cut -f1)"
}

backup_zip() {
    local source="$1"
    local dest="${2:-$BACKUP_DIR/backup_$(date +%Y%m%d).zip}"
    log "Creating zip backup of $source to $dest"
    sudo zip -r "$dest" "$source" || die "Failed to create zip backup"
    log "Backup completed successfully. Size: $(du -h "$dest" | cut -f1)"
}

backup_dd() {
    local source="$1"
    local dest="${2:-$BACKUP_DIR/disk_clone_$(date +%Y%m%d).img}"
    log "Creating disk clone of $source to $dest"
    sudo dd if="$source" of="$dest" bs=4M status=progress || die "Failed to create disk clone"
    log "Disk clone completed successfully. Size: $(du -h "$dest" | cut -f1)"
}

# ==================== AV FUNCTIONS ====================

av_scan() {
    local scan_type="$1"
    local target="${2:-/}"
    
    case "$scan_type" in
        clamav)
            log "Starting ClamAV scan on $target"
            if ! command -v clamscan &> /dev/null; then
                log "Installing ClamAV..."
                eval $INSTALL_CMD clamav clamav-daemon
                systemctl enable clamav-freshclam --now
                systemctl enable clamav-daemon --now
            fi
            sudo clamscan --recursive --infected --bell --log=/var/log/clamav/nas-scan-$(date +%Y%m%d).log "$target" || die "ClamAV scan failed"
            ;;
        maldet)
            log "Starting LMD/Maldet scan on $target"
            if ! command -v maldet &> /dev/null; then
                log "Installing Maldet..."
                eval $INSTALL_CMD linux-malware-detect
                maldet --update-ver
                maldet --update
            fi
            sudo maldet -a "$target" || die "Maldet scan failed"
            ;;
        rkhunter)
            log "Starting Rootkit Hunter scan"
            if ! command -v rkhunter &> /dev/null; then
                log "Installing RKHunter..."
                eval $INSTALL_CMD rkhunter
            fi
            sudo rkhunter --check --sk --rwo || die "RKHunter scan failed"
            ;;
        chkrootkit)
            log "Starting chkrootkit scan"
            if ! command -v chkrootkit &> /dev/null; then
                log "Installing chkrootkit..."
                eval $INSTALL_CMD chkrootkit
            fi
            sudo chkrootkit || die "chkrootkit scan failed"
            ;;
        *)
            die "Invalid AV scan type: $scan_type"
            ;;
    esac
    log "Security scan completed successfully"
}

av_clamav_schedule() {
    local target="$1"
    CRON_FILE="/etc/cron.weekly/clamav-nas-scan"
    log "Scheduling weekly ClamAV scan for $target"
    backup_file "$CRON_FILE"
    cat > "$CRON_FILE" <<EOF
#!/bin/sh
clamscan -r "$target" --bell -i --exclude-dir="^/proc|^/sys|^/dev" -l /var/log/clamav/nas-scan-$(date +%Y%m%d).log
EOF
    chmod +x "$CRON_FILE"
    log "Weekly ClamAV scan scheduled for $target"
}

av_maldet_monitor() {
    local target="$1"
    log "Enabling Maldet monitoring for $target"
    if ! command -v maldet &> /dev/null; then
        log "Installing Maldet..."
        eval $INSTALL_CMD linux-malware-detect
        maldet --update-ver
        maldet --update
    fi
    backup_file /etc/maldetect/conf.maldet
    cat > /etc/maldetect/conf.maldet <<EOF
email_alert="1"
email_addr="root@localhost"
quarantine_hits="1"
quarantine_clean="0"
scan_tmpdir_paths="/tmp /var/tmp"
scan_user_access="1"
default_monitor_mode="/usr/local/maldetect/monitor_paths"
EOF
    echo "$target" > /usr/local/maldetect/monitor_paths
    maldet --monitor /usr/local/maldetect/monitor_paths
    systemctl enable maldet --now || true
    log "Maldet monitoring enabled for $target"
}

update_av_databases() {
    log "Updating ClamAV databases..."
    if ! command -v freshclam &> /dev/null; then
        log "Installing ClamAV..."
        eval $INSTALL_CMD clamav clamav-daemon
    fi
    sudo freshclam || die "Failed to update ClamAV databases"
    
    if command -v maldet &> /dev/null; then
        log "Updating Maldet signatures..."
        sudo maldet -u || die "Failed to update Maldet signatures"
    else
        log "Maldet not installed, skipping update"
    fi
    
    if command -v rkhunter &> /dev/null; then
        log "Updating RKHunter databases..."
        sudo rkhunter --update || die "Failed to update RKHunter databases"
    else
        log "RKHunter not installed, skipping update"
    fi
    
    log "All AV databases updated successfully"
}

# ==================== SYSTEM FUNCTIONS ====================

system_update() {
    log "Updating system packages..."
    eval $UPDATE_CMD || die "Failed to update system"
    log "System packages updated successfully"
}

# ==================== STORAGE MANAGEMENT ====================

storage_manage() {
    case "$1" in
        list)
            log "Listing storage devices"
            sudo lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT,LABEL,UUID || die "Failed to list storage devices"
            ;;
        format)
            local device="$2"
            local fstype="${3:-ext4}"
            log "Formatting $device as $fstype"
            sudo mkfs.$fstype "$device" || die "Failed to format device"
            log "Device $device formatted as $fstype"
            ;;
        mount)
            local device="$2"
            local mountpoint="$3"
            log "Mounting $device to $mountpoint"
            sudo mkdir -p "$mountpoint" || die "Failed to create mountpoint"
            sudo mount -o noatime,nodiratime "$device" "$mountpoint" || die "Failed to mount device"
            log "Device $device mounted at $mountpoint"
            ;;
        umount)
            local mountpoint="$2"
            log "Unmounting $mountpoint"
            sudo umount "$mountpoint" || die "Failed to unmount"
            log "Mountpoint $mountpoint unmounted"
            ;;
        info)
            local device="$2"
            log "Showing info for $device"
            sudo hdparm -I "$device" || die "Failed to get device info"
            sudo smartctl -a "$device" || die "Failed to get SMART info"
            ;;
        *)
            die "Invalid storage command: $1"
            ;;
    esac
}

# ==================== NFS MANAGEMENT ====================

nfs_manage() {
    case "$1" in
        install)
            log "Installing NFS server..."
            eval $INSTALL_CMD $NFS_SERVICE
            systemctl enable --now $NFS_SERVICE
            log "NFS server installed and enabled"
            ;;
        add-share)
            local path="$2"
            local clients="$3"
            local options="${4:-rw,sync,no_subtree_check,no_root_squash}"
            log "Adding NFS share $path for clients $clients"
            backup_file /etc/exports
            if grep -qE "^[[:space:]]*$(printf '%q' "$path")[[:space:]]" /etc/exports; then
                sed -ri "s|^(\s*)$(printf '%q' "$path").*|\1${path} ${clients}(${options})|" /etc/exports
            else
                echo "$path $clients($options)" | sudo tee -a /etc/exports > /dev/null
            fi
            sudo exportfs -ra || die "Failed to export shares"
            sudo systemctl restart $NFS_SERVICE || die "Failed to restart NFS"
            log "NFS share added successfully"
            ;;
        *)
            die "Invalid NFS command: $1"
            ;;
    esac
}

# ==================== SAMBA MANAGEMENT ====================

samba_manage() {
    case "$1" in
        install)
            log "Installing Samba..."
            eval $INSTALL_CMD samba samba-common-bin
            systemctl enable --now smbd nmbd
            log "Samba installed and enabled"
            ;;
        add-share)
            local name="$2"
            local path="$3"
            local users="$4"
            local writable="${5:-yes}"
            log "Adding Samba share $name for path $path"
            backup_file /etc/samba/smb.conf
            echo "[$name]" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   path = $path" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   valid users = $users" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   writable = $writable" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   browsable = yes" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   guest ok = no" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   read only = no" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   create mask = 0660" | sudo tee -a /etc/samba/smb.conf > /dev/null
            echo "   directory mask = 0770" | sudo tee -a /etc/samba/smb.conf > /dev/null
            sudo mkdir -p "$path"
            sudo chown root:"$users" "$path"
            sudo chmod 2770 "$path"
            sudo systemctl restart smbd || die "Failed to restart Samba"
            log "Samba share $name added successfully"
            ;;
        *)
            die "Invalid Samba command: $1"
            ;;
    esac
}

# ==================== SSHFS MANAGEMENT ====================

sshfs_manage() {
    case "$1" in
        install)
            log "Installing SSHFS..."
            case $DISTRO in
                debian|ubuntu)
                    eval $INSTALL_CMD sshfs
                    ;;
                opensuse*)
                    eval $INSTALL_CMD fuse-sshfs
                    ;;
            esac
            modprobe fuse
            backup_file /etc/fuse.conf
            touch /etc/fuse.conf
            if grep -q '^\s*#\s*user_allow_other' /etc/fuse.conf; then
                sed -ri 's/^\s*#\s*user_allow_other/user_allow_other/' /etc/fuse.conf
            elif ! grep -q '^\s*user_allow_other' /etc/fuse.conf; then
                echo "user_allow_other" >> /etc/fuse.conf
            fi
            log "SSHFS installed and configured"
            ;;
        mount)
            local user="$2"
            local host="$3"
            local remote_path="$4"
            local local_path="$5"
            log "Mounting $user@$host:$remote_path to $local_path"
            mkdir -p "$local_path"
            sudo sshfs -o allow_other,default_permissions $user@$host:$remote_path $local_path || die "SSHFS mount failed"
            log "SSHFS mount successful"
            ;;
        *)
            die "Invalid SSHFS command: $1"
            ;;
    esac
}

# ==================== FIREWALL MANAGEMENT ====================

firewall_manage() {
    case "$FIREWALL_TYPE" in
        firewalld)
            if ! command -v firewall-cmd &> /dev/null; then
                log "Installing firewalld..."
                eval $INSTALL_CMD firewalld
                systemctl enable --now firewalld
            fi
            case "$1" in
                add-port)
                    local port="$2"
                    local proto="${3:-tcp}"
                    log "Adding firewalld port $port/$proto"
                    firewall-cmd --permanent --add-port="$port/$proto" || die "Failed to add port"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Port $port/$proto added"
                    ;;
                remove-port)
                    local port="$2"
                    local proto="${3:-tcp}"
                    log "Removing firewalld port $port/$proto"
                    firewall-cmd --permanent --remove-port="$port/$proto" || die "Failed to remove port"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Port $port/$proto removed"
                    ;;
                add-service)
                    local service="$2"
                    log "Adding firewalld service $service"
                    firewall-cmd --permanent --add-service="$service" || die "Failed to add service"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Service $service added"
                    ;;
                remove-service)
                    local service="$2"
                    log "Removing firewalld service $service"
                    firewall-cmd --permanent --remove-service="$service" || die "Failed to remove service"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Service $service removed"
                    ;;
                add-source)
                    local source="$2"
                    log "Adding firewalld source $source"
                    firewall-cmd --permanent --zone=public --add-source="$source" || die "Failed to add source"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Source $source added"
                    ;;
                remove-source)
                    local source="$2"
                    log "Removing firewalld source $source"
                    firewall-cmd --permanent --zone=public --remove-source="$source" || die "Failed to remove source"
                    firewall-cmd --reload || die "Failed to reload firewall"
                    log "Source $source removed"
                    ;;
                list)
                    log "Listing firewalld configuration"
                    firewall-cmd --list-all || die "Failed to list firewall configuration"
                    ;;
                *)
                    die "Invalid firewalld command"
                    ;;
            esac
            ;;
        *)
            die "Unsupported firewall type: $FIREWALL_TYPE"
            ;;
    esac
}

# ==================== FAIL2BAN MANAGEMENT ====================

fail2ban_manage() {
    case "$1" in
        install)
            log "Installing fail2ban..."
            eval $INSTALL_CMD fail2ban
            systemctl enable --now fail2ban
            backup_file /etc/fail2ban/jail.local
            cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
bantime  = 10m
findtime  = 10m
maxretry = 5
destemail = root@localhost
action = %(action_mwl)s

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5

[samba]
enabled = true
port = 137,138,139,445
filter = samba
logpath = /var/log/samba/log.%(netbios_name)s
maxretry = 5
EOF
            log "Fail2ban installed and configured for SSH and Samba"
            ;;
        enable-jail)
            local jail="$2"
            log "Enabling fail2ban jail $jail"
            fail2ban-client set "$jail" enabled true || die "Failed to enable jail $jail"
            systemctl restart fail2ban || die "Failed to restart fail2ban"
            log "Jail $jail enabled"
            ;;
        disable-jail)
            local jail="$2"
            log "Disabling fail2ban jail $jail"
            fail2ban-client set "$jail" enabled false || die "Failed to disable jail $jail"
            systemctl restart fail2ban || die "Failed to restart fail2ban"
            log "Jail $jail disabled"
            ;;
        status)
            log "Fail2ban status:"
            fail2ban-client status || die "Failed to get fail2ban status"
            log "Detailed jail status:"
            fail2ban-client status sshd || true
            fail2ban-client status samba || true
            ;;
        *)
            die "Invalid fail2ban command"
            ;;
    esac
}

# ==================== RAID MANAGEMENT ====================

raid_manage() {
    if ! command -v mdadm &> /dev/null; then
        log "Installing mdadm..."
        eval $INSTALL_CMD mdadm
    fi

    case "$1" in
        create)
            local level="$2"
            local devices="$3"
            local name="${4:-md0}"
            log "Creating RAID $level array $name with devices: $devices"
            mdadm --create --verbose "/dev/$name" --level="$level" --raid-devices=$(echo $devices | wc -w) $devices || die "Failed to create RAID"
            mkfs.ext4 "/dev/$name" || die "Failed to create filesystem"
            log "RAID array created successfully"
            ;;
        add)
            local array="$2"
            local device="$3"
            log "Adding device $device to array $array"
            mdadm --add "/dev/$array" "$device" || die "Failed to add device to array"
            log "Device $device added to array $array"
            ;;
        remove)
            local array="$2"
            local device="$3"
            log "Removing device $device from array $array"
            mdadm --fail "/dev/$array" "$device" && mdadm --remove "/dev/$array" "$device" || die "Failed to remove device from array"
            log "Device $device removed from array $array"
            ;;
        stop)
            local array="$2"
            log "Stopping RAID array $array"
            mdadm --stop "/dev/$array" || die "Failed to stop RAID array"
            log "RAID array $array stopped"
            ;;
        status)
            log "RAID Status:"
            cat /proc/mdstat || die "Failed to check RAID status"
            mdadm --detail --scan || die "Failed to scan RAID devices"
            ;;
        save)
            log "Saving RAID configuration"
            mdadm --detail --scan > /etc/mdadm.conf || die "Failed to save RAID config"
            ;;
        *)
            die "Invalid RAID command"
            ;;
    esac
}

# ==================== NETWORK MANAGEMENT ====================

network_manage() {
    case "$1" in
        list-interfaces)
            log "Listing network interfaces"
            ip -br addr show || die "Failed to list interfaces"
            ;;
        set-ip)
            local iface="$2"
            local ip="$3"
            local netmask="${4:-24}"
            log "Setting IP $ip/$netmask on $iface"
            ip addr add "$ip/$netmask" dev "$iface" || die "Failed to set IP"
            log "IP address $ip/$netmask set on $iface"
            ;;
        set-gateway)
            local gw="$2"
            log "Setting default gateway $gw"
            ip route add default via "$gw" || die "Failed to set gateway"
            log "Default gateway set to $gw"
            ;;
        set-dns)
            local dns="$2"
            log "Setting DNS server $dns"
            echo "nameserver $dns" | tee /etc/resolv.conf > /dev/null || die "Failed to set DNS"
            log "DNS server set to $dns"
            ;;
        test)
            log "Testing network connectivity"
            ping -c 4 8.8.8.8 || die "Network test failed"
            log "Network test successful"
            ;;
        bridge)
            local name="$2"
            local ifaces="$3"
            log "Creating bridge $name with interfaces $ifaces"
            ip link add name $name type bridge || die "Failed to create bridge"
            for iface in $ifaces; do
                ip link set $iface master $name || die "Failed to add interface to bridge"
            done
            ip link set $name up || die "Failed to bring up bridge"
            log "Bridge $name created successfully"
            ;;
        bond)
            local name="$2"
            local mode="$3"
            local ifaces="$4"
            log "Creating bond $name in mode $mode with interfaces $ifaces"
            ip link add $name type bond mode $mode || die "Failed to create bond"
            for iface in $ifaces; do
                ip link set $iface master $name || die "Failed to add interface to bond"
            done
            ip link set $name up || die "Failed to bring up bond"
            log "Bond $name created successfully"
            ;;
        *)
            die "Invalid network command"
            ;;
    esac
}

# ==================== SERVICE MANAGEMENT ====================

service_manage() {
    local service="$2"
    case "$1" in
        start)
            log "Starting service $service"
            systemctl start "$service" || die "Failed to start service"
            log "Service $service started"
            ;;
        stop)
            log "Stopping service $service"
            systemctl stop "$service" || die "Failed to stop service"
            log "Service $service stopped"
            ;;
        restart)
            log "Restarting service $service"
            systemctl restart "$service" || die "Failed to restart service"
            log "Service $service restarted"
            ;;
        enable)
            log "Enabling service $service"
            systemctl enable "$service" || die "Failed to enable service"
            log "Service $service enabled"
            ;;
        disable)
            log "Disabling service $service"
            systemctl disable "$service" || die "Failed to disable service"
            log "Service $service disabled"
            ;;
        status)
            log "Status of service $service"
            systemctl status "$service" --no-pager || die "Failed to get service status"
            ;;
        mask)
            log "Masking service $service"
            systemctl mask "$service" || die "Failed to mask service"
            log "Service $service masked"
            ;;
        unmask)
            log "Unmasking service $service"
            systemctl unmask "$service" || die "Failed to unmask service"
            log "Service $service unmasked"
            ;;
        *)
            die "Invalid service command"
            ;;
    esac
}

# ==================== USER MANAGEMENT ====================

user_manage() {
    case "$1" in
        add)
            local user="$2"
            local shell="${3:-/bin/bash}"
            log "Adding user $user with shell $shell"
            useradd -m -s "$shell" "$user" || die "Failed to add user"
            passwd "$user" || die "Failed to set password"
            log "User $user added successfully"
            ;;
        remove)
            local user="$2"
            log "Removing user $user"
            userdel -r "$user" || die "Failed to remove user"
            log "User $user removed successfully"
            ;;
        list)
            log "Listing users"
            cut -d: -f1 /etc/passwd || die "Failed to list users"
            ;;
        passwd)
            local user="$2"
            log "Changing password for $user"
            passwd "$user" || die "Failed to change password"
            log "Password changed for $user"
            ;;
        add-to-group)
            local user="$2"
            local group="$3"
            log "Adding $user to group $group"
            usermod -aG "$group" "$user" || die "Failed to add user to group"
            log "User $user added to group $group"
            ;;
        remove-from-group)
            local user="$2"
            local group="$3"
            log "Removing $user from group $group"
            gpasswd -d "$user" "$group" || die "Failed to remove user from group"
            log "User $user removed from group $group"
            ;;
        list-groups)
            local user="$2"
            log "Listing groups for $user"
            groups "$user" || die "Failed to list groups"
            ;;
        lock)
            local user="$2"
            log "Locking account for $user"
            passwd -l "$user" || die "Failed to lock account"
            log "Account $user locked"
            ;;
        unlock)
            local user="$2"
            log "Unlocking account for $user"
            passwd -u "$user" || die "Failed to unlock account"
            log "Account $user unlocked"
            ;;
        *)
            die "Invalid user command"
            ;;
    esac
}

# ==================== MAIN FUNCTION ====================

main() {
    # Handle global options first
    local MONITORING=false
    local DISK_HEALTH=false
    
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --help|-h)
                if [[ -n "${2:-}" ]] && [[ "$2" == --* ]]; then
                    module_help "${2#--}"
                    exit 0
                else
                    show_help
                    exit 0
                fi
                ;;
            --version|-v)
                echo "Enterprise NAS Management Tool v$VERSION"
                exit 0
                ;;
            --verbose)
                VERBOSE=true
                shift
                ;;
            --monitor)
                MONITORING=true
                shift
                ;;
            --disk-health)
                DISK_HEALTH=true
                shift
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
    done

    init
    
    # Check for monitoring flags
    if $MONITORING; then
        monitor_iostat 2 5
    fi
    
    if $DISK_HEALTH; then
        check_disk_health
    fi

    # Process module commands
    case "$1" in
        --backup)
            shift
            case "$1" in
                --tar)
                    shift
                    backup_tar "$1" "$2"
                    ;;
                --zip)
                    shift
                    backup_zip "$1" "$2"
                    ;;
                --dd)
                    shift
                    backup_dd "$1" "$2"
                    ;;
                *)
                    die "Invalid backup action\n$(module_help backup)"
                    ;;
            esac
            ;;
        --av)
            shift
            case "$1" in
                --clamav)
                    shift
                    av_scan "clamav" "$1"
                    ;;
                --maldet)
                    shift
                    av_scan "maldet" "$1"
                    ;;
                --rkhunter)
                    av_scan "rkhunter"
                    ;;
                --chkrootkit)
                    av_scan "chkrootkit"
                    ;;
                --update-databases)
                    update_av_databases
                    ;;
                --clamav-schedule)
                    shift
                    av_clamav_schedule "$1"
                    ;;
                --maldet-monitor)
                    shift
                    av_maldet_monitor "$1"
                    ;;
                *)
                    die "Invalid AV action\n$(module_help av)"
                    ;;
            esac
            ;;
        --system)
            shift
            system_update
            ;;
        --monitor)
            shift
            case "$1" in
                --iostat)
                    shift
                    monitor_iostat "$1" "$2"
                    ;;
                --netdata)
                    shift
                    monitor_netdata "$1"
                    ;;
                --disk-health)
                    check_disk_health
                    ;;
                *)
                    die "Invalid monitor action\n$(module_help monitor)"
                    ;;
            esac
            ;;
        --storage)
            shift
            storage_manage "$@"
            ;;
        --nfs)
            shift
            nfs_manage "$@"
            ;;
        --samba)
            shift
            samba_manage "$@"
            ;;
        --sshfs)
            shift
            sshfs_manage "$@"
            ;;
        --firewall)
            shift
            firewall_manage "$@"
            ;;
        --fail2ban)
            shift
            fail2ban_manage "$@"
            ;;
        --raid)
            shift
            raid_manage "$@"
            ;;
        --network)
            shift
            network_manage "$@"
            ;;
        --service)
            shift
            service_manage "$@"
            ;;
        --user)
            shift
            user_manage "$@"
            ;;
        *)
            show_help
            exit 1
            ;;
    esac
}

# Initialize and run
main "$@"
