#! /bin/bash
#   USB Class values for reference
#   Value	Hex Value	Descriptor
#   1		1		Audio 
#   2		2 		CDC-Control 
#   3		3		HID 
#   5		5		Physical 
#   6		6		Image (subclass & protocol must be 1) 
#   7		7		Printer 
#   8		8		Mass-Storage 
#   9		9		HUB 
#   10		A		CDC-Data 
#   11 		B		Chip/Smart Card 

usb_log="/var/log/mountusb.log"

if [ "$1" = "testonly" ]; then
   ls /proc/scsi/ >> /var/log/usb
   cat /proc/scsi/usb-storage-*/* | grep -i "Attached: Yes" >>/var/log/usb
   numdevices=`/bin/cat /proc/scsi/usb-storage-*/* | /bin/grep -i "Attached: Yes" | /opt/bin/wc -l`
   echo "numdevices=$numdevices" >>$usb_log
   if [ $numdevices -gt 2 ]; then
      #Need to raise alarm here
      /nn/bin/AddNnuDiagLog -mOperatingSystem -lmountusb.log -wE -sE -cF -v1003 "Two USB storage devices are attached to the system. This is an unsupported configuration."
      echo `date` " two or more" >>$usb_log 
      exit 1
   else
      echo `date` " less than two" >>$usb_log 
      exit 0
   fi
fi

#First see if a device is mounted 
if `mount | grep /dev/sdc 2>&1 >/dev/null`; then
   #Next check to see what type it is based on class
   if `cat /proc/scsi/usb-storage-*/* | grep -i "attached: yes" 2>&1 >/dev/null`; then
      echo `date` " WARNING: USB storage device already mounted" >>$usb_log
      exit 0
   else #non-supported scenario
      echo `date` " Device mounted as a SCSI device but a non-mass storage device. Unsupported" >>$usb_log
      exit 1
   fi
fi

#No mounted device, see if one is attached
if ! `cat /proc/scsi/usb-storage-*/* | grep -i "attached: yes" 2>&1 >/dev/null`; then
   echo `date` "ERROR : no mass storage device attached" >>$usb_log
   cat /proc/bus/usb/devices >>$usb_log
   exit 1
fi

#Check to see if 2 storage devices are attached
numdevices=`/bin/cat /proc/scsi/usb-storage-*/* | /bin/grep -i "Attached: Yes" | /opt/bin/wc -l`
echo "numdevices=$numdevices" >>$usb_log
if [ $numdevices -gt 2 ]; then
   #Need to raise alarm here
   /nn/bin/AddNnuDiagLog -mOperatingSystem -lmountusb.log -wE -sE -cF -v1003 "Two USB storage devices are attached to the system. This is an unsupported configuration."
   echo `date` " two or more" >>$usb_log
   exit 1
fi


#device found, mount at /mnt/usb
if `mount | grep /mnt/usb 2>&1 >/dev/null`; then
   echo `date` " ERROR: A device is already mounted at /mnt/usb" >>$usb_log
fi

if [ ! -d /mnt/usb ]; then
   mkdir /mnt/usb/
fi

if `mount -t vfat /dev/sdc1 /mnt/usb`; then
   echo `date` "INFO: USB device mounted at /mnt/usb" >>$usb_log
   exit 0
else
   mountret=$?
   echo `date` " ERROR: mount usb at /mnt/usb failed with return $mountret" >>$usb_log
   rmdir /mnt/usb/
   exit 1
fi
