#!/usr/bin/perl

######################################################################
# 
# usb2guid and sd2usbguid: by greenfly <greenfly@greenfly.org>
#
# This function gets passed the a scsi hard drive device and returns 
# the GUID assigned to it from /proc/scsi/usb-storage-0/.
#
# it basically is the complement to usbguid2sd
#
# usage: sd2usbguid <scsi drive>
#
# example: sd2usbguid sda
# output: 05e307020000000000000000
# 
# 
######################################################################

use strict;

my $scsi_drive = shift;
my $logfile = "/var/log/syslog";
my $procdir = "/proc/scsi/usb-storage-0";

my $scsi_host;
my $guid;

$scsi_host = get_scsi_host_from_drive($scsi_drive);
$guid = get_guid_from_scsi_host($scsi_host);

print "$guid";




######################################################################
#
# this function gets passed a scsi host and reads all the files in
# $procdir to determine what guid it was assigned
#
sub get_guid_from_scsi_host
{
   my $scsi_host = shift;
   my $file;
   my $guid;

   opendir(DIR, $procdir) or die "can't opendir $procdir: $!";
   while (defined($file = readdir(DIR))) 
   {
      next if $file =~ /^\.\.?$/;	# skip . and ..

      open FILE, "$procdir/$file" or die "can't open $procdir/$file: $!";
      while(<FILE>)
      {
	 if(/Host (\w+): usb-storage/)
	 {
	    last if($1 ne $scsi_host);
	 }
	 elsif(/GUID: (\w+)/)
	 {
	    $guid = $1;
	 }
      }
      close FILE;
   }
   closedir(DIR);
   return $guid;
}


######################################################################
#
# this function gets passed a scsi drive, such as "sda" and reads 
# $logfile to determine what scsi host it was assigned
#
sub get_scsi_host_from_drive
{
   my $scsi_drive = shift;
   my $scsi_host;

   open SYSLOG, $logfile or die "Can't open $logfile: $!";

   while(<SYSLOG>)
   {
      if(/kernel: Attached scsi disk $scsi_drive at (\w+),/)
      {
	 $scsi_host = $1;
      }
   }
   close SYSLOG;

   return "$scsi_host";
}
