#!/usr/bin/env bash
# ==============================================================================
# Irbis OS - Unified Command Line Interface (CLI)
# Path: /usr/local/bin/irbis
# Description: Outil officiel d'administration, de maintenance et de secours Irbis OS
# ==============================================================================

set -e

# Version du CLI
IRBIS_CLI_VERSION="1.2.0"

# Palette de couleurs ANSI
BOLD='\033[1m'
DIM='\033[2m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'

# Chemins système de référence
CONFIG_DIR="/etc/irbis-os"
SYSTEM_CONFIG="${CONFIG_DIR}/config.json"
STORAGE_ROOT="/mnt/storage"
SERVICE_NAME="irbis-os.service"
MAINTENANCE_FLAG="${CONFIG_DIR}/maintenance.flag"
NOTIFICATIONS_LOG="/var/log/irbis-os/notifications.log"

# Helper privilèges d'élévation
run_privileged() {
    if [ "$(id -u)" -eq 0 ]; then
        "$@"
    else
        if command -v sudo >/dev/null 2>&1; then
            sudo "$@"
        else
            echo -e "${RED}[ERREUR] Droits administrateur (root ou sudo) requis pour exécuter cette action.${NC}" >&2
            exit 1
        fi
    fi
}

# Bannière stylisée
print_banner() {
    echo -e "${CYAN}${BOLD}"
    echo "  ___      _     _         ___  ____  "
    echo " |_ _|___ | |__ (_)___    / _ \/ ___| "
    echo "  | |/ __|| '_ \| / __|  | | | \___ \ "
    echo "  | | |   | |_) | \__ \  | |_| |___) |"
    echo " |___|_|  |_.__/|_|___/   \___/|____/ "
    echo -e "${NC}${DIM} Unified System Management CLI (v${IRBIS_CLI_VERSION})${NC}\n"
}

# ------------------------------------------------------------------------------
# AIDE / USAGE
# ------------------------------------------------------------------------------
show_help() {
    print_banner
    echo -e "${BOLD}UTILISATION :${NC}"
    echo -e "  irbis <commande> [options]\n"
    echo -e "${BOLD}COMMANDES PRINCIPALES :${NC}"
    echo -e "  ${GREEN}status${NC}                          Affiche le tableau de bord système en direct (CPU, RAM, Disques, IP)"
    echo -e "  ${GREEN}logs${NC} [-f] [-n <lignes>]         Consulte les journaux d'exécution du backend Irbis OS"
    echo -e "  ${GREEN}restart${NC}                         Redémarre le service applicatif Irbis OS"
    echo -e "  ${GREEN}start${NC} / ${GREEN}stop${NC} / ${GREEN}reload${NC}          Contrôle le démon système Irbis OS"
    echo -e "  ${GREEN}storage${NC} <sous-commande>         Supervise les disques, pools Btrfs, scrubs et snapshots"
    echo -e "  ${GREEN}docker${NC} <sous-commande>          Gère les applications installées depuis l'App Store"
    echo -e "  ${GREEN}user${NC} <sous-commande>            Administration des utilisateurs et de leurs arborescences"
    echo -e "  ${GREEN}backup${NC} create [nom]             Génère une sauvegarde instantanée des configurations et états"
    echo -e "  ${GREEN}update${NC} check                    Vérifie la disponibilité de mises à jour système\n"
    echo -e "${BOLD}COMMANDES DE SECOURS & URGENCE :${NC}"
    echo -e "  ${YELLOW}reset-admin-password${NC} [pass]     Réinitialise le mot de passe du compte administrateur web"
    echo -e "  ${YELLOW}reset-network${NC}                    Réinitialise les cartes réseau en DHCP automatique"
    echo -e "  ${YELLOW}unlock-user${NC} <username>          Débloque un compte utilisateur temporairement verrouillé"
    echo -e "  ${YELLOW}support-bundle${NC}                  Génère une archive diagnostic complète pour le support\n"
    echo -e "${BOLD}EXPLOITATION & PERFORMANCE :${NC}"
    echo -e "  ${CYAN}maintenance${NC} [on|off|status]     Bascule le NAS en mode maintenance technique"
    echo -e "  ${CYAN}benchmark${NC} <disk|net>            Mesure les performances d'E/S stockage ou de débit réseau"
    echo -e "  ${CYAN}notify${NC} [options]                Injecte un événement dans le centre de notifications\n"
    echo -e "${BOLD}OPTIONS GLOBALES :${NC}"
    echo -e "  -h, --help                      Affiche cette aide"
    echo -e "  -v, --version                   Affiche la version du CLI"
    echo ""
}

# ------------------------------------------------------------------------------
# 1. STATUS : DASHBOARD CONSOLE EN DIRECT
# ------------------------------------------------------------------------------
cmd_status() {
    print_banner

    # 1. Informations Système & Version
    local os_pretty="Debian GNU/Linux"
    if [ -f /etc/os-release ]; then
        # shellcheck disable=SC1091
        os_pretty=$(grep -E '^PRETTY_NAME=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    fi
    local kernel_ver
    kernel_ver=$(uname -r)
    local hostname_val
    hostname_val=$(hostname)
    local uptime_str
    uptime_str=$(uptime -p 2>/dev/null || uptime | awk -F'( |,|:)+' '{print $6,"hrs,"}')

    echo -e "${BOLD}┌── SYSTÈME & MATÉRIEL ────────────────────────────────────────────────────────┐${NC}"
    echo -e "  ${DIM}Hôte       :${NC} ${WHITE}${hostname_val}${NC}"
    echo -e "  ${DIM}Système    :${NC} ${os_pretty} (${kernel_ver})"
    echo -e "  ${DIM}Uptime     :${NC} ${uptime_str}"
    
    # 2. Charge CPU et Mémoire
    local load_avg
    load_avg=$(cat /proc/loadavg 2>/dev/null | awk '{print $1", "$2", "$3}' || echo "N/A")
    local mem_total mem_used mem_percent
    mem_total=$(free -h 2>/dev/null | awk '/^Mem:/ {print $2}')
    mem_used=$(free -h 2>/dev/null | awk '/^Mem:/ {print $3}')
    mem_percent=$(free 2>/dev/null | awk '/^Mem:/ {printf "%.1f", ($3/$2)*100}')

    echo -e "  ${DIM}Charge CPU :${NC} ${load_avg}"
    echo -e "  ${DIM}Mémoire RAM:${NC} ${mem_used} / ${mem_total} (${mem_percent}%)"

    # 3. Réseau & Adresses IP
    echo -e "\n${BOLD}├── RÉSEAU & INTERFACES ────────────────────────────────────────────────────────┤${NC}"
    local ip_addrs
    ip_addrs=$(ip -4 -br addr show 2>/dev/null | grep -v "lo" || echo "Aucune interface active")
    while IFS= read -r line; do
        if [ -n "$line" ]; then
            local iface state ip
            iface=$(echo "$line" | awk '{print $1}')
            state=$(echo "$line" | awk '{print $2}')
            ip=$(echo "$line" | awk '{print $3}')
            local state_color="${GREEN}"
            [ "$state" != "UP" ] && state_color="${YELLOW}"
            echo -e "  ${DIM}${iface}:${NC} ${ip} [${state_color}${state}${NC}]"
        fi
    done <<< "$ip_addrs"

    # 4. Statut des Démons Clés
    echo -e "\n${BOLD}├── ÉTAT DES SERVICES ──────────────────────────────────────────────────────────┤${NC}"
    check_service_status() {
        local sname="$1"
        local label="$2"
        if systemctl is-active --quiet "$sname" 2>/dev/null; then
            echo -e "  ${DIM}${label}:${NC} ${GREEN}${BOLD}● ACTIF${NC}"
        else
            echo -e "  ${DIM}${label}:${NC} ${RED}○ INACTIF${NC}"
        fi
    }
    check_service_status "irbis-os.service" "Backend Irbis OS "
    check_service_status "docker.service"   "Moteur Docker    "
    check_service_status "avahi-daemon.service" "Service mDNS     "
    if systemctl is-active --quiet "NetworkManager.service" 2>/dev/null; then
        echo -e "  ${DIM}Gestionnaire Réseau:${NC} ${GREEN}${BOLD}● ACTIF (NetworkManager)${NC}"
    elif systemctl is-active --quiet "systemd-networkd.service" 2>/dev/null; then
        echo -e "  ${DIM}Gestionnaire Réseau:${NC} ${GREEN}${BOLD}● ACTIF (networkd)${NC}"
    elif systemctl is-active --quiet "networking.service" 2>/dev/null; then
        echo -e "  ${DIM}Gestionnaire Réseau:${NC} ${GREEN}${BOLD}● ACTIF (networking)${NC}"
    else
        echo -e "  ${DIM}Gestionnaire Réseau:${NC} ${YELLOW}○ Non supervisé${NC}"
    fi

    # 5. Stockage & Volumes Montés
    echo -e "\n${BOLD}└── STOCKAGE & POOLS DE DONNÉES ────────────────────────────────────────────────┘${NC}"
    if [ -d "${STORAGE_ROOT}" ]; then
        local storage_df
        storage_df=$(df -h "${STORAGE_ROOT}" 2>/dev/null | tail -n 1)
        local total_space used_space avail_space use_pct
        total_space=$(echo "$storage_df" | awk '{print $2}')
        used_space=$(echo "$storage_df" | awk '{print $3}')
        avail_space=$(echo "$storage_df" | awk '{print $4}')
        use_pct=$(echo "$storage_df" | awk '{print $5}')
        echo -e "  ${DIM}Pool Principal (/mnt/storage) :${NC} ${WHITE}${used_space}${NC} utilisé sur ${WHITE}${total_space}${NC} (Libre: ${GREEN}${avail_space}${NC} / ${use_pct})"
    else
        echo -e "  ${YELLOW}/mnt/storage n'est pas encore initialisé.${NC}"
    fi

    if command -v btrfs >/dev/null 2>&1; then
        local btrfs_check
        btrfs_check=$(btrfs filesystem show 2>/dev/null || true)
        if [ -n "$btrfs_check" ]; then
            echo -e "  ${DIM}Statut Btrfs : Pool multi-disques détecté et actif.${NC}"
        fi
    fi
    echo ""
}

# ------------------------------------------------------------------------------
# 2. LOGS : WRAPPER JOURNALCTL
# ------------------------------------------------------------------------------
cmd_logs() {
    local follow=false
    local lines=100

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -f|--follow)
                follow=true
                shift
                ;;
            -n|--lines)
                lines="$2"
                shift 2
                ;;
            *)
                shift
                ;;
        esac
    done

    echo -e "${CYAN}[+] Consultation des logs Irbis OS (${SERVICE_NAME}) :${NC}\n"
    local journal_cmd="journalctl -u ${SERVICE_NAME} -n ${lines} --no-hostname -o short-iso"
    if [ "$follow" = true ]; then
        journal_cmd="${journal_cmd} -f"
    fi

    run_privileged $journal_cmd
}

# ------------------------------------------------------------------------------
# 3. GESTION DU SERVICE : START / STOP / RESTART / RELOAD
# ------------------------------------------------------------------------------
cmd_service_control() {
    local action="$1"
    echo -e "${CYAN}[+] Exécution : systemctl ${action} ${SERVICE_NAME}...${NC}"
    run_privileged systemctl "$action" "${SERVICE_NAME}"
    sleep 1
    if systemctl is-active --quiet "${SERVICE_NAME}"; then
        echo -e "${GREEN}✓ Le service Irbis OS est désormais ACTIF.${NC}"
    else
        if [ "$action" = "stop" ]; then
            echo -e "${YELLOW}✓ Le service Irbis OS a été arrêté.${NC}"
        else
            echo -e "${RED}✗ Le service Irbis OS n'est pas actif. Consultez les logs avec 'irbis logs'.${NC}"
        fi
    fi
}

# ------------------------------------------------------------------------------
# 4. STORAGE : DISQUES, BTRFS, SCRUB & SNAPSHOTS
# ------------------------------------------------------------------------------
cmd_storage() {
    local sub="$1"
    shift || true

    case "$sub" in
        list|"")
            echo -e "${CYAN}${BOLD}[+] Disques physiques et partitions détectées :${NC}"
            lsblk -o NAME,SIZE,FSTYPE,TYPE,MOUNTPOINT,MODEL
            echo ""
            if command -v btrfs >/dev/null 2>&1; then
                echo -e "${CYAN}${BOLD}[+] Pools et systèmes de fichiers Btrfs :${NC}"
                run_privileged btrfs filesystem show 2>/dev/null || echo "Aucun pool Btrfs actif."
            fi
            echo ""
            if command -v smartctl >/dev/null 2>&1; then
                echo -e "${CYAN}${BOLD}[+] Santé matérielle S.M.A.R.T. sommaire :${NC}"
                for dev in $(lsblk -d -n -o NAME -e 7,11); do
                    local smart_status
                    smart_status=$(run_privileged smartctl -H "/dev/${dev}" 2>/dev/null | grep -i "test result" || echo "Non supporté")
                    echo -e "  /dev/${dev} : ${smart_status}"
                done
            fi
            ;;
        df)
            echo -e "${CYAN}${BOLD}[+] Utilisation de l'espace disque :${NC}"
            df -h -T / /mnt/storage 2>/dev/null || df -h
            ;;
        scrub)
            local action="${1:-status}"
            local path="${2:-${STORAGE_ROOT}}"
            case "$action" in
                start)
                    echo -e "${YELLOW}[+] Démarrage du contrôle de cohérence Btrfs (scrub) sur ${path}...${NC}"
                    run_privileged btrfs scrub start "$path"
                    ;;
                status)
                    echo -e "${CYAN}[+] Statut du contrôle Btrfs sur ${path} :${NC}"
                    run_privileged btrfs scrub status "$path"
                    ;;
                cancel)
                    echo -e "${YELLOW}[+] Annulation du scrub sur ${path}...${NC}"
                    run_privileged btrfs scrub cancel "$path"
                    ;;
                *)
                    echo -e "${RED}Option scrub invalide. Utiliser : start | status | cancel [path]${NC}"
                    ;;
            esac
            ;;
        balance)
            local action="${1:-status}"
            local path="${2:-${STORAGE_ROOT}}"
            case "$action" in
                start)
                    echo -e "${YELLOW}[+] Démarrage du rééquilibrage Btrfs sur ${path}...${NC}"
                    run_privileged btrfs balance start "$path"
                    ;;
                status)
                    echo -e "${CYAN}[+] Statut du rééquilibrage Btrfs sur ${path} :${NC}"
                    run_privileged btrfs balance status "$path"
                    ;;
                cancel)
                    echo -e "${YELLOW}[+] Annulation du balance sur ${path}...${NC}"
                    run_privileged btrfs balance cancel "$path"
                    ;;
                *)
                    echo -e "${RED}Option balance invalide. Utiliser : start | status | cancel [path]${NC}"
                    ;;
            esac
            ;;
        snapshot)
            local action="${1:-list}"
            local snap_dir="${STORAGE_ROOT}/.snapshots"
            case "$action" in
                create)
                    local snap_name="${2:-snap_$(date +%Y%m%d_%H%M%S)}"
                    run_privileged mkdir -p "$snap_dir"
                    echo -e "${CYAN}[+] Création d'un snapshot Btrfs : ${snap_dir}/${snap_name}...${NC}"
                    run_privileged btrfs subvolume snapshot -r "${STORAGE_ROOT}" "${snap_dir}/${snap_name}"
                    echo -e "${GREEN}✓ Snapshot créé avec succès.${NC}"
                    ;;
                list)
                    echo -e "${CYAN}[+] Liste des snapshots Btrfs dans ${snap_dir} :${NC}"
                    if [ -d "$snap_dir" ]; then
                        run_privileged ls -lh "$snap_dir"
                    else
                        echo "Aucun snapshot pour l'instant."
                    fi
                    ;;
                delete)
                    local snap_target="$2"
                    if [ -z "$snap_target" ]; then
                        echo -e "${RED}[ERREUR] Précisez le nom du snapshot à supprimer.${NC}"
                        exit 1
                    fi
                    echo -e "${YELLOW}[+] Suppression du sous-volume snapshot ${snap_dir}/${snap_target}...${NC}"
                    run_privileged btrfs subvolume delete "${snap_dir}/${snap_target}"
                    echo -e "${GREEN}✓ Snapshot supprimé.${NC}"
                    ;;
                *)
                    echo -e "${RED}Option snapshot inconnue. Utiliser : list | create [nom] | delete <nom>${NC}"
                    ;;
            esac
            ;;
        *)
            echo -e "${RED}Sous-commande storage inconnue : ${sub}${NC}"
            echo -e "Utilisation : irbis storage [list | df | scrub | balance | snapshot]"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 5. DOCKER : GESTION DES APPLICATIONS DU STORE
# ------------------------------------------------------------------------------
cmd_docker() {
    if ! command -v docker >/dev/null 2>&1; then
        echo -e "${RED}[ERREUR] Docker n'est pas installé sur ce système.${NC}"
        exit 1
    fi

    local sub="${1:-list}"
    shift || true

    case "$sub" in
        list)
            echo -e "${CYAN}${BOLD}[+] Conteneurs applicatifs Irbis OS :${NC}"
            docker ps -a --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
            ;;
        restart)
            local target="$1"
            [ -z "$target" ] && { echo -e "${RED}[ERREUR] Nom de conteneur requis.${NC}"; exit 1; }
            echo -e "${CYAN}[+] Redémarrage du conteneur ${target}...${NC}"
            docker restart "$target"
            echo -e "${GREEN}✓ Conteneur ${target} redémarré.${NC}"
            ;;
        start)
            local target="$1"
            [ -z "$target" ] && { echo -e "${RED}[ERREUR] Nom de conteneur requis.${NC}"; exit 1; }
            docker start "$target"
            echo -e "${GREEN}✓ Conteneur ${target} démarré.${NC}"
            ;;
        stop)
            local target="$1"
            [ -z "$target" ] && { echo -e "${RED}[ERREUR] Nom de conteneur requis.${NC}"; exit 1; }
            docker stop "$target"
            echo -e "${GREEN}✓ Conteneur ${target} arrêté.${NC}"
            ;;
        logs)
            local target="$1"
            [ -z "$target" ] && { echo -e "${RED}[ERREUR] Nom de conteneur requis.${NC}"; exit 1; }
            shift || true
            docker logs "$target" "$@"
            ;;
        *)
            echo -e "${RED}Sous-commande docker inconnue : ${sub}${NC}"
            echo -e "Utilisation : irbis docker [list | restart <app> | start <app> | stop <app> | logs <app>]"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 6. USER : GESTION DES UTILISATEURS & ARBORESCENCES
# ------------------------------------------------------------------------------
cmd_user() {
    local sub="${1:-list}"
    shift || true

    case "$sub" in
        list)
            echo -e "${CYAN}${BOLD}[+] Utilisateurs répertoriés sur Irbis OS :${NC}"
            if [ -d "${STORAGE_ROOT}/users" ]; then
                for udir in "${STORAGE_ROOT}/users"/*; do
                    if [ -d "$udir" ]; then
                        local uname
                        uname=$(basename "$udir")
                        echo -e "  • ${WHITE}${uname}${NC} (Espace : ${udir})"
                    fi
                done
            else
                echo "Aucun dossier utilisateur sous ${STORAGE_ROOT}/users"
            fi
            ;;
        add)
            local username="$1"
            local password="$2"
            if [ -z "$username" ]; then
                echo -e "${RED}[ERREUR] Veuillez spécifier un nom d'utilisateur : irbis user add <nom>${NC}"
                exit 1
            fi

            # Validation du nom
            if [[ ! "$username" =~ ^[a-zA-Z0-9_-]+$ ]]; then
                echo -e "${RED}[ERREUR] Le nom d'utilisateur ne peut contenir que des caractères alphanumériques, tirets et underscores.${NC}"
                exit 1
            fi

            echo -e "${CYAN}[+] Création de l'arborescence personnelle pour '${username}'...${NC}"
            local user_base="${STORAGE_ROOT}/users/${username}"
            run_privileged mkdir -p \
                "${user_base}/Documents" \
                "${user_base}/Medias" \
                "${user_base}/Musics" \
                "${user_base}/Pictures" \
                "${user_base}/Downloads"

            # Création du compte Linux local s'il n'existe pas déjà
            if ! id "$username" >/dev/null 2>&1; then
                echo -e "${CYAN}[+] Création du compte Linux '${username}'...${NC}"
                run_privileged useradd -m -d "${user_base}" -s /usr/sbin/nologin "$username" 2>/dev/null || true
                if [ -n "$password" ]; then
                    echo "${username}:${password}" | run_privileged chpasswd
                fi
            fi

            run_privileged chown -R "${username}:${username}" "${user_base}" 2>/dev/null || true
            run_privileged chmod 750 "${user_base}"

            echo -e "${GREEN}✓ Utilisateur '${username}' créé avec succès !${NC}"
            echo -e "  Arborescence initialisée :"
            echo -e "  ├── ${user_base}/Documents"
            echo -e "  ├── ${user_base}/Medias"
            echo -e "  ├── ${user_base}/Musics"
            echo -e "  ├── ${user_base}/Pictures"
            echo -e "  └── ${user_base}/Downloads"
            ;;
        *)
            echo -e "${RED}Sous-commande user inconnue : ${sub}${NC}"
            echo -e "Utilisation : irbis user [list | add <username> [password]]"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 7. BACKUP : SAUVEGARDE INSTANTANÉE
# ------------------------------------------------------------------------------
cmd_backup() {
    local sub="${1:-create}"
    shift || true

    case "$sub" in
        create)
            local bname="${1:-irbis-backup-$(date +%Y%m%d_%H%M%S)}"
            local backup_dir="${STORAGE_ROOT}/backups"
            run_privileged mkdir -p "$backup_dir"
            local archive_file="${backup_dir}/${bname}.tar.gz"

            echo -e "${CYAN}[+] Création de l'archive de sauvegarde : ${archive_file}...${NC}"
            run_privileged tar -czf "${archive_file}" \
                -C / \
                --exclude="*.log" \
                etc/irbis-os \
                etc/systemd/network \
                2>/dev/null || true

            echo -e "${GREEN}✓ Sauvegarde générée avec succès : ${archive_file}${NC}"
            ls -lh "${archive_file}"
            ;;
        list)
            echo -e "${CYAN}[+] Sauvegardes existantes dans ${STORAGE_ROOT}/backups :${NC}"
            if [ -d "${STORAGE_ROOT}/backups" ]; then
                ls -lh "${STORAGE_ROOT}/backups"
            else
                echo "Aucune sauvegarde disponible."
            fi
            ;;
        *)
            echo -e "${RED}Sous-commande backup inconnue. Utiliser : create [nom] | list${NC}"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 8. UPDATE : VÉRIFICATION ET APPLICATION DES MISES À JOUR
# ------------------------------------------------------------------------------
cmd_update() {
    local sub="${1:-check}"
    shift || true
    local skip_hash=false
    local target_ver=""

    while [ $# -gt 0 ]; do
        case "$1" in
            --skip-hash|--no-verify)
                skip_hash=true
                shift
                ;;
            *)
                target_ver="$1"
                shift
                ;;
        esac
    done

    case "$sub" in
        check)
            echo -e "${CYAN}[+] Vérification des mises à jour système pour Irbis OS (v${IRBIS_CLI_VERSION})...${NC}"
            if ping -c 1 -W 2 1.1.1.1 >/dev/null 2>&1; then
                echo -e "${GREEN}✓ Connexion Internet active.${NC}"
                echo -e "${GREEN}✓ Votre système Irbis OS est à jour (Version ${IRBIS_CLI_VERSION} - Branche appliance stable).${NC}"
            else
                echo -e "${YELLOW}⚠️ Impossible de joindre les serveurs de mise à jour (Pas d'accès Internet).${NC}"
            fi
            ;;
        apply|install)
            echo -e "${CYAN}[+] Déclenchement de la mise à jour système Irbis OS...${NC}"
            if [ "$skip_hash" = true ]; then
                echo -e "${YELLOW}⚠️ Option --skip-hash active : validation de signature cryptographique ignorée.${NC}"
            fi
            # 1. Tenter via API REST locale si le service répond
            if curl -fsSL -X POST -H "Content-Type: application/json" \
                -d "{\"version\":\"${target_ver}\",\"skipHashVerification\":${skip_hash}}" \
                http://127.0.0.1:4000/api/v1/system/update/ota/apply >/dev/null 2>&1; then
                echo -e "${GREEN}✓ Mise à jour OTA initiée avec succès via l'API locale.${NC}"
                echo -e "${CYAN}Suivez la progression avec : irbis logs -f${NC}"
                return 0
            fi

            # 2. Exécution CLI directe autonome via Node.js
            echo -e "${CYAN}[+] Exécution autonome via le moteur de mise à jour système...${NC}"
            node -e "
              const path = require('path');
              let osUpdateService;
              try {
                osUpdateService = require('/opt/irbis-os/apps/backend/dist/services/system/OsUpdateService.js').osUpdateService;
              } catch {
                osUpdateService = require(path.resolve(process.cwd(), 'apps/backend/dist/services/system/OsUpdateService.js')).osUpdateService;
              }
              osUpdateService.applyOtaUpdate('${target_ver}' || undefined, { skipHashVerification: ${skip_hash} })
                .then(() => {
                  console.log('\x1b[32m✓ Mise à jour Irbis OS appliquée avec succès !\x1b[0m');
                  process.exit(0);
                })
                .catch(err => {
                  console.error('\x1b[31m[ERREUR] Échec de la mise à jour:\x1b[0m', err.message || err);
                  process.exit(1);
                });
            "
            ;;
        *)
            echo -e "${RED}Sous-commande update inconnue. Utiliser : irbis update check OU irbis update apply [--skip-hash] [version]${NC}"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 9. RESCUE : RESET ADMIN PASSWORD
# ------------------------------------------------------------------------------
cmd_reset_admin_password() {
    local new_password="$1"
    if [ -z "$new_password" ]; then
        echo -e "${YELLOW}Veuillez saisir le nouveau mot de passe administrateur :${NC}"
        read -rsp "Nouveau mot de passe : " new_password
        echo ""
        read -rsp "Confirmez le mot de passe : " confirm_password
        echo ""
        if [ "$new_password" != "$confirm_password" ]; then
            echo -e "${RED}[ERREUR] Les deux mots de passe ne correspondent pas.${NC}"
            exit 1
        fi
    fi

    if [ -z "$new_password" ]; then
        echo -e "${RED}[ERREUR] Le mot de passe ne peut être vide.${NC}"
        exit 1
    fi

    echo -e "${CYAN}[+] Réinitialisation du mot de passe administrateur dans les fichiers de configuration...${NC}"

    # Utilisation directe du moteur Node.js pour regénérer le hash scrypt à l'identique de SystemConfigManager.ts
    local node_script="
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

const newPass = process.argv[1];
const targetPaths = [
    '/etc/irbis-os/config.json',
    '/mnt/storage/volume_1/irbis_os/configs/config.json',
    '/mnt/storage/irbis_os/configs/config.json'
];

const salt = crypto.randomBytes(16).toString('hex');
const passwordHash = crypto.scryptSync(newPass, salt, 64).toString('hex');

let updated = 0;

for (const p of targetPaths) {
    if (fs.existsSync(p)) {
        try {
            const raw = fs.readFileSync(p, 'utf8');
            const cfg = JSON.parse(raw);
            if (!cfg.adminUser) {
                cfg.adminUser = { username: 'admin', createdAt: Date.now() };
            }
            cfg.adminUser.passwordHash = passwordHash;
            cfg.adminUser.salt = salt;
            fs.writeFileSync(p, JSON.stringify(cfg, null, 2), 'utf8');
            console.log('✓ Mot de passe mis à jour dans ' + p);
            updated++;
        } catch (e) {
            console.error('Erreur fichier ' + p + ':', e.message);
        }
    }
}

if (updated === 0) {
    // Créer la configuration initiale si inexistante
    const defaultPath = '/etc/irbis-os/config.json';
    fs.mkdirSync('/etc/irbis-os', { recursive: true });
    const cfg = {
        version: '1.0.0-appliance',
        serverName: 'Irbis-NAS',
        timezone: 'UTC',
        adminUser: {
            username: 'admin',
            passwordHash,
            salt,
            createdAt: Date.now()
        },
        storagePools: []
    };
    fs.writeFileSync(defaultPath, JSON.stringify(cfg, null, 2), 'utf8');
    console.log('✓ Fichier créé et initialisé : ' + defaultPath);
}
"

    run_privileged node -e "$node_script" "$new_password"

    echo -e "${GREEN}✓ Le mot de passe administrateur a été réinitialisé avec succès !${NC}"
    echo -e "${CYAN}Identifiant : admin${NC}"
}

# ------------------------------------------------------------------------------
# 10. RESCUE : RESET NETWORK (DHCP)
# ------------------------------------------------------------------------------
cmd_reset_network() {
    echo -e "${YELLOW}${BOLD}[!] Réinitialisation d'urgence de la configuration réseau...${NC}"

    local networkd_file="/etc/systemd/network/20-wired.network"
    echo -e "${CYAN}[+] Génération de la configuration DHCP universelle (${networkd_file})...${NC}"

    run_privileged mkdir -p /etc/systemd/network
    cat <<'EOF' | run_privileged tee "$networkd_file" >/dev/null
[Match]
Name=en* eth* enp*

[Network]
DHCP=yes

[DHCPv4]
RouteMetric=10
EOF

    echo -e "${CYAN}[+] Redémarrage des services réseau (systemd-networkd & resolved)...${NC}"
    run_privileged systemctl restart systemd-networkd systemd-resolved 2>/dev/null || true

    sleep 2
    echo -e "${GREEN}✓ Interfaces réseau réinitialisées en DHCP automatique :${NC}"
    ip -4 -br addr show 2>/dev/null || ip a
}

# ------------------------------------------------------------------------------
# 11. RESCUE : UNLOCK USER
# ------------------------------------------------------------------------------
cmd_unlock_user() {
    local username="$1"
    if [ -z "$username" ]; then
        echo -e "${RED}[ERREUR] Précisez le nom d'utilisateur à débloquer : irbis unlock-user <nom>${NC}"
        exit 1
    fi

    echo -e "${CYAN}[+] Déverrouillage du compte utilisateur '${username}'...${NC}"
    # Si faillock ou pam_tally2 est utilisé
    if command -v faillock >/dev/null 2>&1; then
        run_privileged faillock --user "$username" --reset 2>/dev/null || true
    fi

    # Déverrouille le compte Linux sous Debian si verrouillé par passwd -l
    run_privileged passwd -u "$username" 2>/dev/null || true

    echo -e "${GREEN}✓ Le compte '${username}' a été débloqué.${NC}"
}

# ------------------------------------------------------------------------------
# 12. SUPPORT BUNDLE : GÉNÉRATEUR DE DIAGNOSTIC
# ------------------------------------------------------------------------------
cmd_support_bundle() {
    local timestamp
    timestamp=$(date +%Y%m%d_%H%M%S)
    local bundle_name="irbis-diagnostic-${timestamp}"
    local tmp_dir="/tmp/${bundle_name}"
    local output_dir="${STORAGE_ROOT}"

    [ ! -d "$output_dir" ] && output_dir="/tmp"
    local final_archive="${output_dir}/${bundle_name}.tar.gz"

    echo -e "${CYAN}${BOLD}[+] Création du rapport de support technique (${bundle_name})...${NC}"
    run_privileged mkdir -p "${tmp_dir}"

    echo -e "  ├── Collecte des 500 dernières lignes de logs Irbis OS..."
    run_privileged journalctl -u "${SERVICE_NAME}" -n 500 --no-pager > "${tmp_dir}/irbis-os-service.log" 2>/dev/null || true

    echo -e "  ├── Collecte des 500 dernières lignes de logs noyau (dmesg)..."
    run_privileged dmesg -T 2>/dev/null | tail -n 500 > "${tmp_dir}/dmesg.log" || true

    echo -e "  ├── Collecte des informations disques et partitionnement..."
    run_privileged lsblk -f > "${tmp_dir}/lsblk.txt" 2>/dev/null || true
    run_privileged parted -l > "${tmp_dir}/parted.txt" 2>/dev/null || true
    run_privileged cp /etc/fstab "${tmp_dir}/fstab.txt" 2>/dev/null || true

    echo -e "  ├── Collecte de la télémétrie S.M.A.R.T..."
    if command -v smartctl >/dev/null 2>&1; then
        for dev in $(lsblk -d -n -o NAME -e 7,11); do
            run_privileged smartctl -a "/dev/${dev}" > "${tmp_dir}/smart-${dev}.txt" 2>/dev/null || true
        done
    fi

    echo -e "  ├── Collecte de l'état des conteneurs Docker..."
    if command -v docker >/dev/null 2>&1; then
        docker ps -a > "${tmp_dir}/docker-containers.txt" 2>/dev/null || true
        docker stats --no-stream > "${tmp_dir}/docker-stats.txt" 2>/dev/null || true
    fi

    echo -e "  ├── Collecte de la configuration réseau..."
    ip a > "${tmp_dir}/ip-addr.txt" 2>/dev/null || true
    ip r > "${tmp_dir}/ip-route.txt" 2>/dev/null || true

    echo -e "  └── Archivage et compression..."
    run_privileged tar -czf "${final_archive}" -C /tmp "${bundle_name}"
    run_privileged rm -rf "${tmp_dir}"

    echo -e "\n${GREEN}${BOLD}✓ Rapport de support généré avec succès :${NC}"
    echo -e "  ${WHITE}${final_archive}${NC} ($(du -h "${final_archive}" | awk '{print $1}'))"
    echo -e "${DIM}  Vous pouvez transférer cette archive pour diagnostiquer votre NAS.${NC}"
}

# ------------------------------------------------------------------------------
# 13. MODE MAINTENANCE
# ------------------------------------------------------------------------------
cmd_maintenance() {
    local action="${1:-status}"
    case "$action" in
        on)
            echo -e "${YELLOW}${BOLD}[!] Activation du mode maintenance...${NC}"
            run_privileged mkdir -p "${CONFIG_DIR}"
            run_privileged touch "${MAINTENANCE_FLAG}"
            if [ -d "${STORAGE_ROOT}/irbis_os/configs" ]; then
                run_privileged touch "${STORAGE_ROOT}/irbis_os/configs/maintenance.flag"
            fi
            
            # Mise en pause des conteneurs Docker non essentiels
            if command -v docker >/dev/null 2>&1; then
                local running_containers
                running_containers=$(docker ps -q)
                if [ -n "$running_containers" ]; then
                    echo -e "${CYAN}[+] Mise en pause des conteneurs applicatifs...${NC}"
                    docker pause $running_containers 2>/dev/null || true
                fi
            fi
            echo -e "${GREEN}✓ Mode maintenance ACTIVÉ.${NC}"
            ;;
        off)
            echo -e "${CYAN}[+] Désactivation du mode maintenance...${NC}"
            run_privileged rm -f "${MAINTENANCE_FLAG}"
            if [ -d "${STORAGE_ROOT}/irbis_os/configs" ]; then
                run_privileged rm -f "${STORAGE_ROOT}/irbis_os/configs/maintenance.flag"
            fi

            # Dé-pause des conteneurs Docker
            if command -v docker >/dev/null 2>&1; then
                local paused_containers
                paused_containers=$(docker ps -q -f "status=paused")
                if [ -n "$paused_containers" ]; then
                    echo -e "${CYAN}[+] Reprise des conteneurs applicatifs...${NC}"
                    docker unpause $paused_containers 2>/dev/null || true
                fi
            fi
            echo -e "${GREEN}✓ Mode maintenance DÉSACTIVÉ.${NC}"
            ;;
        status)
            if [ -f "${MAINTENANCE_FLAG}" ]; then
                echo -e "${YELLOW}Mode maintenance : ACTIF${NC}"
            else
                echo -e "${GREEN}Mode maintenance : INACTIF (Mode normal)${NC}"
            fi
            ;;
        *)
            echo -e "${RED}Option maintenance inconnue. Utiliser : irbis maintenance [on | off | status]${NC}"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 14. BENCHMARK : DISK & RÉSEAU
# ------------------------------------------------------------------------------
cmd_benchmark() {
    local target="${1:-disk}"
    shift || true

    case "$target" in
        disk)
            local test_path="${1:-${STORAGE_ROOT}}"
            if [ ! -d "$test_path" ]; then
                test_path="/tmp"
            fi
            local test_file="${test_path}/.irbis_bench_temp"
            echo -e "${CYAN}${BOLD}[+] Benchmark de performance E/S disque sur : ${test_path}${NC}"
            echo -e "  [1/2] Test d'écriture séquentielle (1 Go, sync direct)..."
            run_privileged dd if=/dev/zero of="${test_file}" bs=1M count=1024 conv=fdatasync status=progress
            echo ""
            echo -e "  [2/2] Test de lecture séquentielle..."
            # Purge du cache OS en RAM pour une mesure réelle
            run_privileged sh -c 'sync; echo 3 > /proc/sys/kernel/drop_caches' 2>/dev/null || true
            run_privileged dd if="${test_file}" of=/dev/null bs=1M count=1024 status=progress
            run_privileged rm -f "${test_file}"
            echo -e "\n${GREEN}✓ Benchmark disque terminé avec succès.${NC}"
            ;;
        net)
            local arg="$1"
            if [ "$arg" = "server" ]; then
                if ! command -v iperf3 >/dev/null 2>&1; then
                    echo -e "${RED}[ERREUR] iperf3 n'est pas installé. Exécutez : apt-get install iperf3${NC}"
                    exit 1
                fi
                echo -e "${GREEN}[+] Démarrage du serveur iperf3 sur le port 5201 (Ctrl+C pour quitter)...${NC}"
                iperf3 -s
            else
                echo -e "${CYAN}[+] Test de connectivité et latence locale :${NC}"
                local default_gateway
                default_gateway=$(ip route show default 2>/dev/null | awk '{print $3}' | head -n 1)
                if [ -n "$default_gateway" ]; then
                    echo -e "  Passerelle par défaut (${default_gateway}) :"
                    ping -c 4 "$default_gateway"
                else
                    echo -e "${YELLOW}Aucune passerelle par défaut détectée.${NC}"
                fi
                echo ""
                echo -e "${DIM}Pour démarrer un serveur iperf3 de test débit : 'irbis benchmark net server'${NC}"
            fi
            ;;
        *)
            echo -e "${RED}Type de benchmark inconnu. Utiliser : irbis benchmark <disk|net>${NC}"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 15. NOTIFY : NOTIFICATION SYSTÈME & CLI
# ------------------------------------------------------------------------------
cmd_notify() {
    local level="info"
    local title="Notification Irbis OS"
    local message=""

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --level=*)
                level="${1#*=}"
                shift
                ;;
            --title=*)
                title="${1#*=}"
                shift
                ;;
            --message=*)
                message="${1#*=}"
                shift
                ;;
            *)
                if [ -z "$message" ]; then
                    message="$1"
                fi
                shift
                ;;
        esac
    done

    if [ -z "$message" ]; then
        echo -e "${RED}[ERREUR] Message requis : irbis notify --title=\"...\" --message=\"...\"${NC}"
        exit 1
    fi

    local timestamp
    timestamp=$(date -Iseconds)
    local log_entry="[${timestamp}] [${level^^}] [${title}] ${message}"

    run_privileged mkdir -p "$(dirname "${NOTIFICATIONS_LOG}")"
    echo "$log_entry" | run_privileged tee -a "${NOTIFICATIONS_LOG}" >/dev/null

    # Notification vers l'API locale si le backend est actif
    if curl -s -f -X POST http://127.0.0.1:4000/api/v1/system/notify \
        -H "Content-Type: application/json" \
        -d "{\"level\":\"${level}\",\"title\":\"${title}\",\"message\":\"${message}\"}" >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Notification émise et transmise à l'interface web : [${level^^}] ${title}${NC}"
    else
        echo -e "${GREEN}✓ Notification enregistrée dans le journal système : [${level^^}] ${title}${NC}"
    fi
}

# ------------------------------------------------------------------------------
# DISPATCHER PRINCIPAL
# ------------------------------------------------------------------------------
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi

    local command="$1"
    shift

    case "$command" in
        status)
            cmd_status "$@"
            ;;
        logs)
            cmd_logs "$@"
            ;;
        restart)
            cmd_service_control "restart"
            ;;
        start)
            cmd_service_control "start"
            ;;
        stop)
            cmd_service_control "stop"
            ;;
        reload)
            cmd_service_control "reload"
            ;;
        storage)
            cmd_storage "$@"
            ;;
        docker)
            cmd_docker "$@"
            ;;
        user)
            cmd_user "$@"
            ;;
        backup)
            cmd_backup "$@"
            ;;
        update)
            cmd_update "$@"
            ;;
        reset-admin-password)
            cmd_reset_admin_password "$@"
            ;;
        reset-network)
            cmd_reset_network "$@"
            ;;
        unlock-user)
            cmd_unlock_user "$@"
            ;;
        support-bundle)
            cmd_support_bundle "$@"
            ;;
        maintenance)
            cmd_maintenance "$@"
            ;;
        benchmark)
            cmd_benchmark "$@"
            ;;
        notify)
            cmd_notify "$@"
            ;;
        -v|--version|version)
            echo "irbis v${IRBIS_CLI_VERSION}"
            ;;
        -h|--help|help)
            show_help
            ;;
        *)
            echo -e "${RED}[ERREUR] Commande inconnue : ${command}${NC}"
            echo -e "Exécutez '${BOLD}irbis --help${NC}' pour afficher la liste des commandes disponibles."
            exit 1
            ;;
    esac
}

main "$@"
