#!/usr/bin/perl

# Found here: http://greenfly.org/tips/usb_drive.html

######################################################################
# 
# usb2guid and sd2usbguid: by greenfly <greenfly@greenfly.org>
#
# This function gets passed the $PRODUCT environment variable for a usb
# device, and returns which scsi hard drive that GUID was assigned to
#
# it basically is the complement to sd2usbguid
#
# usage: usbguid2sd <usb guid>
#
# example: usbguid2sd 05e30702 (or 5e3/702/02 which is $PRODUCT to hotplug)
# output: sda
# 
######################################################################

use strict;

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

my $scsi_host;
my $scsi_drive;

# change the guid to the format for /proc/scsi/usb-storage-0/
if($guid =~ m#^([A-Za-z0-9]+)/([A-Za-z0-9]+)/(\d+)$#)
{
   $guid = sprintf("%04s%04s", $1, $2);
}
$scsi_host = get_scsi_host_from_guid($guid);
$scsi_drive = get_drive_from_scsi_host($scsi_host);

print "$scsi_drive";



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

   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/)
	 {
	    $scsi_host = $1;
	 }
	 if(/GUID: (\w+)/)
	 {
	    return $scsi_host if($1 =~ /^$guid/);
	 }
      }
      close FILE;
   }
   closedir(DIR);
   return 0;
}


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

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

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

   return "$scsi_device";
}