summaryrefslogtreecommitdiff
path: root/usbguid2sd
blob: b243532a462ebed79b52f31d4c7ce30f6d42af1d (plain)
  1. #!/usr/bin/perl
  2. ######################################################################
  3. # usb2guid and sd2usbguid: by greenfly <greenfly@greenfly.org>
  4. #
  5. # This function gets passed the $PRODUCT environment variable for a usb
  6. # device, and returns which scsi hard drive that GUID was assigned to
  7. #
  8. # it basically is the complement to sd2usbguid
  9. #
  10. # usage: usbguid2sd <usb guid>
  11. #
  12. # example: usbguid2sd 05e30702 (or 5e3/702/02 which is $PRODUCT to hotplug)
  13. # output: sda
  14. #
  15. ######################################################################
  16. use strict;
  17. my $guid = shift;
  18. my $logfile = "/var/log/syslog";
  19. my $procdir = "/proc/scsi/usb-storage-0";
  20. my $scsi_host;
  21. my $scsi_drive;
  22. # change the guid to the format for /proc/scsi/usb-storage-0/
  23. if($guid =~ m#^([A-Za-z0-9]+)/([A-Za-z0-9]+)/(\d+)$#)
  24. {
  25. $guid = sprintf("%04s%04s", $1, $2);
  26. }
  27. $scsi_host = get_scsi_host_from_guid($guid);
  28. $scsi_drive = get_drive_from_scsi_host($scsi_host);
  29. print "$scsi_drive";
  30. ######################################################################
  31. #
  32. # this function gets passed a guid and reads all the files in
  33. # $procdir to determine what scsi host it was assigned
  34. #
  35. sub get_scsi_host_from_guid
  36. {
  37. my $guid = shift;
  38. my $file;
  39. my $scsi_host;
  40. opendir(DIR, $procdir) or die "can't opendir $procdir: $!";
  41. while (defined($file = readdir(DIR)))
  42. {
  43. next if $file =~ /^\.\.?$/; # skip . and ..
  44. open FILE, "$procdir/$file" or die "can't open $procdir/$file: $!";
  45. while(<FILE>)
  46. {
  47. if(/Host (\w+): usb-storage/)
  48. {
  49. $scsi_host = $1;
  50. }
  51. if(/GUID: (\w+)/)
  52. {
  53. return $scsi_host if($1 =~ /^$guid/);
  54. }
  55. }
  56. close FILE;
  57. }
  58. closedir(DIR);
  59. return 0;
  60. }
  61. ######################################################################
  62. #
  63. # this function gets passed a scsi host, such as "scsi1" and reads
  64. # $logfile to determine what drive it was assigned
  65. #
  66. sub get_drive_from_scsi_host
  67. {
  68. my $scsi_host = shift;
  69. my $scsi_device;
  70. open SYSLOG, $logfile or die "Can't open $logfile: $!";
  71. while(<SYSLOG>)
  72. {
  73. if(/kernel: Attached scsi .*disk (\w+) at $scsi_host,/)
  74. {
  75. $scsi_device = $1;
  76. }
  77. }
  78. close SYSLOG;
  79. return "$scsi_device";
  80. }