#!/usr/bin/perl

# setting following because I think it will solve my buffering problem
$| = 1;

$sd_mount=`df -k | grep "^/dev/sd" | awk -f /usr/local/bin/device_parse`;
@mount_array=split(',',$sd_mount);

$usb_avail=`fdisk -l 2>/dev/null | grep "^/dev/sd" | awk -f /usr/local/bin/device_parse`;
$new_usb_avail=`fdisk -l 2>/dev/null | grep "/dev/sd" | awk -f /usr/local/bin/fdisk_device_parse`;

if ( $new_usb_avail =~ "^end" ) {
  print "Done";
  sleep 5;
  exit(0);
}
else {
  @usb_array=split(',',$new_usb_avail);
  
  foreach $usb_dev ( @usb_array ) {
    foreach $disk_mount ( @mount_array ) {
      if ( $disk_mount =~ /$usb_dev/ ) {
        # nothing to do disk is mounted
      }
      else {
        #print "Checking to see if disk is partitioned....";
        $usb_part=`export DISK=$usb_dev; fdisk -l $usb_dev | awk -f /usr/local/bin/fdisk_parse`;
        if ( $usb_part == 0 ) {
          print "Disk is not partitioned. Running sfdisk ";
	  if ( -f "/tmp/partition" ) { `rm /tmp/partition`;}
	  `sfdisk  -l $usb_dev 2>&1 | awk -f /usr/local/bin/sfdisk_parse > /tmp/partition`;
          `sfdisk $usb_dev < /tmp/partition`;
	  $usb_file = $usb_dev . "1";
          print "device is $usb_file\n";
	  `mkfs -t ext3 $usb_file`;
	  print "Enter the name for the disk: ";
          $name = <STDIN>;
          chop($name);
          if ( $usb_file =~ /sda1/ ) { 
            `mount /dev/sda1 /mnt/sda1`;
            `chmod 777 /mnt/sda1`;
            `touch /mnt/sda1/$name`;
            `umount /mnt/sda1`;
          }
          if ( $usb_file =~ /sdb1/ ) { 
            `mount /dev/sdb1 /mnt/sdb1`;
            `chmod 777 /mnt/sdb1`;
            `touch /mnt/sdb1/$name`;
            `umount /mnt/sdb1`;
          }
          #print $usb_dev;
	  #`fdisk $usb_dev`;
          exit(0);
        }
      }
    }
  }
}
  
print "Done";
