#!/bin/bash
# zfs_disks_pools.sh
# Liste les disques physiques avec appartenance au pool ZFS
# Colonnes : DISK | PARTITION/BY-ID | SERIAL | SIZE | POOL

# echo -e "DISK\tPARTITION/BY-ID\tSERIAL\tSIZE\tPOOL"

for pool in $(zpool list -H -o name); do
  zpool list -v "$pool" | awk 'NR>1 {print $1}' | while read -r dev; do
    # ignorer mirror/raidz/spares/etc. ET les noms de pool
    if [[ "$dev" =~ ^mirror|^raidz|^logs|^cache|^spares|^special ]]; then
      continue
    fi
    if [[ "$dev" == "$pool" ]]; then
      continue
    fi

    # résolution du vrai périphérique
    if [[ -e "/dev/disk/by-id/$dev" ]]; then
      real_dev=$(readlink -f "/dev/disk/by-id/$dev")
    else
      real_dev="$dev"
    fi

    # trouver le disque parent (/dev/sdX ou /dev/nvmeXnY)
    parent=$(lsblk -dn -no PKNAME "$real_dev" 2>/dev/null)
    if [[ -n "$parent" ]]; then
      disk="/dev/$parent"
    else
      disk="$real_dev"
    fi

    # interroger uniquement le disque parent pour SERIAL et SIZE
    serial=$(lsblk -dn -o SERIAL "$disk" 2>/dev/null | tr -d ' ')
    size=$(lsblk -dn -o SIZE "$disk" 2>/dev/null)

    echo -e "${disk}\t${dev}\t${serial:-?}\t${size:-?}\t${pool}"
  done
done | column -t