use Win32::Registry;

my ($Disk, $Drive) = ('Disk', 'PhysicalDrive');
$Disk = $Drive = 'CdRom' if ( @ARGV && $ARGV[0] =~ m!^-?(cd|CdRom|dvd|dvdrom)$!io );

my $Disks = "SYSTEM\\CurrentControlSet\\Services\\$Disk\\Enum";

my ($DEBUG, $P,$usage) = (0, 1, "\ndisks[.pl] [-0]\n");

for my $o (@ARGV) {
  $P = 0     if ( $o =~ /^-?0/ );
  $DEBUG = 1 if ( $o =~ /^-?d(e(b(ug?)?)?)?$/ );
}

my %Enum;
$main::HKEY_LOCAL_MACHINE->Open($Disks, $Enum) || die "RegOpen: $!";
$Enum->GetValues(\%Enum);

sub sp($$)
{
   my ($s, $l) = @_;
   my $len = length($s);
   $s .= (' ' x ($l - $len)) if ($l > $len);
   return $s;
}

sub h2a($)
{
  my ($h) = @_;
  my $r = '';
  for (my $i = 0; $i < length($h); $i += 2)
  {
    my $v = hex(substr($h, $i, 2));
    $r .= chr($v) if ( $v > 32 );
  }
  return $r;
}

my $count = $Enum{Count}[2];
if ( $count )
{
   for (my $i=0; $i < $count; ++$i)
   {
      my $e = $Enum{$i}[2];
      if ( $e )
      {
         print $e, "\n" if ( $DEBUG );
         print "$Drive$i: ";

         my ($b, $t, $v, $p, $r, $m);

         #USBSTOR\Disk&Ven_DCB&Prod______HS-HD&Rev_2.23\000111111111&0
         if ( $e =~ m!^([^\\]+)\\([^&]+)&Ven_+([^&]+)&Prod_+([^&]+)&Rev_+([^\\]+)\\(.+)$! )
         {
            ($b, $t, $v, $p, $r, $m) = ($1, $2, $3, $4, $5, $6);
         }

         #IDE\DiskST3300831A______________________________3.01____\2020202020202020202020204E33304638323947
         #IDE\DiskST94019A________________________________3.09____\5&1545bf8&0&0.0.0
         elsif ( $P && $e =~ m!^([^\\]+)\\(Disk|CdRom)_?([^_\\]+)_+([^_\\]+)_+\\(.+)$! )
         {
            ($b, $t, $v, $p, $r, $m) = ($1, $2, "?", $3, $4, $5);
            $v = "Seagate" if ( substr($p, 0, 2) eq "ST" );
            $m = h2a($m) if ( $m =~ m!([0-9A-F][0-9A-F])+$!i );
         }

         #IDE\CdRom_NEC_DVD_RW_ND-4570A____________________1.03____\5&8932dc6&0&0.1.0
         #IDE\CdRomOptiarc_DVD_RW_AD-7203A_________________1.04____\6&5c1bc22&0&0.1.0
         #IDE\DiskWDC_WD1002FBYS-02A6B0___________________03.00C06\5&36a55c2a&0&0.0.0
         elsif ( $P && $e =~ m!^([^\\]+)\\(Disk|CdRom)_?([^_\\]+)_+((DVD_RW_)?[^_\\]+)_+([^_\\]+)_*\\(.+)$! )
         {
            ($b, $t, $v, $p, $r, $m) = ($1, $2, $3, $4, $6, $7);
            $m = h2a($m) if ( $m =~ m!([0-9A-F][0-9A-F])+$!i );
         }

         if ( $P && $b ) { print sp("$b\\$t", 12), " ",sp($v,8), " ",sp($p,17), " ",sp($r,8), " / $m\n"; }
         else            { print "$e\n"; }
      }
   }
}

1;
