#!/usr/bin/env bash

#
# Script de test pour récupérer les informations détaillées de la RAM
# Usage: sudo bash test_ram_info.sh
#

set -e

echo "======================================"
echo "Test de détection des infos RAM"
echo "======================================"
echo ""

# Vérifier si dmidecode est disponible
if ! command -v dmidecode &>/dev/null; then
    echo "❌ dmidecode n'est pas installé"
    exit 1
fi

echo "✓ dmidecode trouvé: $(command -v dmidecode)"
echo ""

# Test 1: Informations générales sur la mémoire (type 16 = Physical Memory Array)
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Type 16: Physical Memory Array"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
sudo dmidecode -t 16
echo ""

# Test 2: Informations détaillées sur les barrettes (type 17 = Memory Device)
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Type 17: Memory Device (détaillé)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
sudo dmidecode -t 17
echo ""

# Test 3: Extraction des champs clés
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Extraction des données structurées"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Compter les slots totaux
slots_total=$(sudo dmidecode -t 16 2>/dev/null | awk -F: '/Number Of Devices/ {gsub(/^[ \t]+/,"",$2); print $2}' | head -1)
echo "📊 Slots totaux: ${slots_total:-N/A}"

# Compter les slots utilisés
slots_used=0
while IFS= read -r line; do
    if [[ "$line" =~ Size.*[0-9]+.*[GM]B ]]; then
        slots_used=$((slots_used + 1))
    fi
done < <(sudo dmidecode -t 17 2>/dev/null)
echo "📊 Slots utilisés: $slots_used"

# Extraire les informations par barrette
echo ""
echo "📋 Détails par barrette:"
echo "┌────────────┬─────────┬────────┬──────────┬──────────────────────┐"
echo "│ Slot       │ Taille  │ Type   │ Vitesse  │ Fabricant            │"
echo "├────────────┼─────────┼────────┼──────────┼──────────────────────┤"

sudo dmidecode -t 17 2>/dev/null | awk '
BEGIN {
    slot = ""
    size = ""
    type = ""
    speed = ""
    manu = ""
}
/^Handle/ {
    # Nouveau handle - afficher les données précédentes
    if (slot != "" && size != "" && size !~ /No Module Installed/) {
        printf "│ %-10s │ %-7s │ %-6s │ %-8s │ %-20s │\n", slot, size, type, speed, manu
    }
    slot = ""
    size = ""
    type = ""
    speed = ""
    manu = ""
}
/Locator:/ && !/Bank/ {
    slot = $2
    gsub(/_/, "", slot)
}
/Size:/ {
    if ($2 == "No") {
        size = "Empty"
    } else if ($2 ~ /[0-9]+/) {
        size = $2 " " $3
    }
}
/Type:/ && !/Detail/ && !/Error/ {
    type = $2
}
/Speed:/ && !/Configured/ {
    speed = $2 " " $3
}
/Manufacturer:/ {
    manu = ""
    for (i = 2; i <= NF; i++) {
        manu = manu $i " "
    }
    gsub(/^[ \t]+|[ \t]+$/, "", manu)
}
END {
    # Afficher la dernière entrée
    if (slot != "" && size != "" && size !~ /No Module Installed/) {
        printf "│ %-10s │ %-7s │ %-6s │ %-8s │ %-20s │\n", slot, size, type, speed, manu
    }
}
'

echo "└────────────┴─────────┴────────┴──────────┴──────────────────────┘"
echo ""

# Test 4: Générer un JSON similaire à ce qui sera utilisé
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "JSON généré (format similaire au script bench.sh)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

dimm_layout="[]"

dimm_data=$(sudo dmidecode -t 17 | grep -E 'Locator:|Size:|Type:|Speed:|Manufacturer:' | \
    awk '
        /Locator:/ && !/Bank/ { slot=$2; gsub(/_/, "", slot) }
        /Size:/ && /[0-9]+ [GM]B/ {
            size=$2;
            if ($3 == "GB") size=size*1024;
            if ($3 == "MB") size=size;
        }
        /Type:/ && !/Detail/ { type=$2 }
        /Speed:/ && /MHz/ { speed=$2 }
        /Manufacturer:/ {
            manu="";
            for(i=2; i<=NF; i++) manu=manu $i " ";
            gsub(/^[ \t]+|[ \t]+$/, "", manu);
            printf "%s;%s;%s;%s;%s\n", slot, size, type, speed, manu
        }')

if command -v jq &>/dev/null; then
    while IFS=';' read -r slot size type speed manu; do
        [[ -z "$slot" ]] && continue
        entry=$(jq -n \
            --arg slot "$slot" \
            --arg size_mb "$size" \
            --arg type "$type" \
            --arg speed_mhz "$speed" \
            --arg manu "$manu" \
            '{
                slot: $slot,
                size_mb: ($size_mb | tonumber? // 0),
                type: $type,
                speed_mhz: ($speed_mhz | tonumber? // 0),
                manufacturer: $manu
            }')
        dimm_layout=$(echo "$dimm_layout" | jq --argjson e "$entry" '. + [$e]')
    done <<< "$dimm_data"

    echo "$dimm_layout" | jq '.'
else
    echo "⚠️  jq non disponible - impossible de générer le JSON"
fi

echo ""
echo "======================================"
echo "✅ Test terminé"
echo "======================================"
