#!/usr/bin/perl
use warnings;
use strict;
use autodie;
use Data::Dump qw(dump);

my ($before, $delimiter, $after) = ( ''=>' | '=> "\n" ); # double space for display
   ($before, $delimiter, $after) = ( '"'=>'","'=> '"'."\n" ) if @ARGV;

my $zfs;
open(my $zpool, '-|', 'zpool status');
my $name = 'zfs';
my $vdev = '';
while(<$zpool>) {
	chomp;
	$name = $1 if /^\s+pool:\s(\S+)/;
	$vdev = $1 if /^\s+(raid\S+|spare|log|cache)/;
	$zfs->{$1} = join(' ', $name, $vdev) if /^\s+(sd\S+)/;
}
warn "# zfs ",dump($zfs);

my $md;
open(my $mdstat, '<', '/proc/mdstat');
while(<$mdstat>) {
	chomp;
	if ( m/(md\d+)\s+:\s+active\s+(\S+)\s+(.+)/ ) {
		my ( $nr, $raid ) = ( $1, $2 );
		foreach my $dev ( split(/\s+/, $3) ) {
			my $d = $1 if $dev =~ m{(sd\w+)\d+};
			$md->{$d} = "$nr $raid $dev";
		}
	}
}
warn "# md ",dump($md);

open(my $lsscsi, '-|', 'lsscsi --size -v');

print $before, join($delimiter, qw(id type name dev size pert_of path) ), $after;

while(my $line = <$lsscsi>) {
	chomp($line);
#	warn "## $line\n";

	my @l = $line =~ m{(^\S+)\s+(\S+)\s+(.+)\s+(\S+)\s+(\S+)};

	my $dev = $l[3];
	$dev =~ s{/dev/}{};
	warn "# dev $dev\n";

	push @l,
		exists $zfs->{$dev} ? $zfs->{$dev} :
		exists $md->{$dev} ? $md->{$dev} :
		'-';

	my $v = <$lsscsi>;
	chomp($v);
	push @l, $1 if $v =~ m/\[(.+)\]/;
	print $before,join($delimiter,@l),$after;
};
