#!/usr/bin/env bash

#
# Test rapide des données SMART pour tous les disques
#

set -e

export PATH="/usr/sbin:/sbin:$PATH"

# Couleurs
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}  Test SMART - Santé des Disques${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════${NC}"
echo ""

# Vérifier smartctl
if ! command -v smartctl &> /dev/null; then
    echo -e "${RED}✗ smartctl non installé${NC}"
    echo "Installer avec: sudo apt-get install smartmontools"
    exit 1
fi

# Lister les disques physiques
physical_disks=$(lsblk -d -n -o NAME,TYPE | grep 'disk' | awk '{print $1}')

for disk in $physical_disks; do
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}Disque: /dev/$disk${NC}"
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

    # Ignorer les disques vides
    size_bytes=$(lsblk -d -n -b -o SIZE /dev/$disk)
    if [[ "$size_bytes" -eq 0 ]]; then
        echo -e "${YELLOW}⚠ Disque vide, ignoré${NC}"
        echo ""
        continue
    fi

    # Infos de base
    model=$(sudo smartctl -i /dev/$disk 2>/dev/null | grep 'Device Model:' | sed 's/.*: *//' || echo "Unknown")
    [[ -z "$model" ]] && model=$(sudo smartctl -i /dev/$disk 2>/dev/null | grep 'Model Number:' | sed 's/.*: *//' || echo "Unknown")

    echo "Modèle: $model"

    # Test de santé
    health=$(sudo smartctl -H /dev/$disk 2>/dev/null | grep 'SMART overall-health' | awk '{print $NF}')
    if [[ "$health" == "PASSED" ]]; then
        echo -e "Santé: ${GREEN}✓ PASSED${NC}"
    elif [[ "$health" == "FAILED" ]]; then
        echo -e "Santé: ${RED}✗ FAILED - REMPLACER IMMÉDIATEMENT${NC}"
    else
        echo "Santé: Inconnu (SMART peut-être non supporté)"
    fi

    # Données SMART importantes
    smart_data=$(sudo smartctl -A /dev/$disk 2>/dev/null)

    if [[ -n "$smart_data" ]]; then
        # Heures de fonctionnement
        power_hours=$(echo "$smart_data" | awk '/Power_On_Hours|Power On Hours/ {print $10}' | head -1)
        if [[ -n "$power_hours" ]]; then
            days=$((power_hours / 24))
            years=$(echo "scale=1; $power_hours / 8760" | bc)
            echo "Temps de fonctionnement: $power_hours heures ($days jours / $years ans)"
        fi

        # Cycles d'alimentation
        power_cycles=$(echo "$smart_data" | awk '/Power_Cycle_Count|Start_Stop_Count/ {print $10}' | head -1)
        [[ -n "$power_cycles" ]] && echo "Cycles d'alimentation: $power_cycles"

        # Température
        temp=$(echo "$smart_data" | awk '/Temperature_Celsius|Airflow_Temperature/ {print $10}' | head -1)
        if [[ -n "$temp" ]]; then
            if [[ $temp -lt 50 ]]; then
                echo -e "Température: ${GREEN}${temp}°C${NC}"
            elif [[ $temp -lt 60 ]]; then
                echo -e "Température: ${YELLOW}${temp}°C (surveiller)${NC}"
            else
                echo -e "Température: ${RED}${temp}°C (SURCHAUFFE)${NC}"
            fi
        fi

        # Secteurs réalloués (CRITIQUE)
        realloc=$(echo "$smart_data" | awk '/Reallocated_Sector_Ct/ {print $10}' | head -1)
        if [[ -n "$realloc" ]]; then
            if [[ $realloc -eq 0 ]]; then
                echo -e "Secteurs réalloués: ${GREEN}$realloc${NC}"
            elif [[ $realloc -lt 10 ]]; then
                echo -e "Secteurs réalloués: ${YELLOW}$realloc (début de défaillance)${NC}"
            else
                echo -e "Secteurs réalloués: ${RED}$realloc (DÉFAILLANCE - planifier remplacement)${NC}"
            fi
        fi

        # Secteurs en attente (TRÈS CRITIQUE)
        pending=$(echo "$smart_data" | awk '/Current_Pending_Sector/ {print $10}' | head -1)
        if [[ -n "$pending" ]]; then
            if [[ $pending -eq 0 ]]; then
                echo -e "Secteurs en attente: ${GREEN}$pending${NC}"
            else
                echo -e "Secteurs en attente: ${RED}$pending (DÉFAILLANCE IMMINENTE - sauvegarder maintenant)${NC}"
            fi
        fi

        # Erreurs CRC
        crc=$(echo "$smart_data" | awk '/UDMA_CRC_Error_Count/ {print $10}' | head -1)
        if [[ -n "$crc" ]]; then
            if [[ $crc -eq 0 ]]; then
                echo -e "Erreurs CRC: ${GREEN}$crc${NC}"
            else
                echo -e "Erreurs CRC: ${YELLOW}$crc (vérifier le câble SATA)${NC}"
            fi
        fi

        # Pour SSD: Wear Leveling
        rota=$(lsblk -d -n -o ROTA /dev/$disk)
        if [[ "$rota" == "0" ]]; then
            wear=$(echo "$smart_data" | awk '/Wear_Leveling_Count/ {print $4}' | head -1)
            if [[ -n "$wear" ]]; then
                if [[ $wear -gt 50 ]]; then
                    echo -e "Usure SSD: ${GREEN}$wear%${NC}"
                elif [[ $wear -gt 20 ]]; then
                    echo -e "Usure SSD: ${YELLOW}$wear% (surveiller)${NC}"
                else
                    echo -e "Usure SSD: ${RED}$wear% (fin de vie proche)${NC}"
                fi
            fi
        fi
    else
        echo -e "${YELLOW}⚠ Données SMART non disponibles pour ce disque${NC}"
    fi

    echo ""
done

echo -e "${BLUE}════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✓ Test SMART terminé${NC}"
echo ""
echo "Pour plus de détails sur un disque:"
echo "  sudo smartctl -a /dev/sdX"
echo ""
echo "Documentation complète: ./SMART_GUIDE.md"
echo -e "${BLUE}════════════════════════════════════════════════════════${NC}"
