#!/bin/bash
# Modified on 8/7/2006 to wait before searching in /proc/partitions
#          added beep sound after successfull adding entry to fstab
#
function cleanup()
{
  rm -rf /tmp/_FSTAB_HMC_
  exit 1
}
function Beep()
{
    echo -en "\007" > /dev/console
    sleep 2
    echo -en "\007" > /dev/console
    sleep 1
    echo -en "\007" > /dev/console
}
function findID()
{
   hwinfo --usb > /tmp/_FSTAB_HMC_/hwinfo.out
   device=$1

   mydevice=${device%%[0-9]}
   found=0
   while read line ; do
     case "$line" in
	 *Unique\ ID:*)
  	    UNIQUEID="${line##*Unique ID: }"
		;;
	 *Device\ File:*)
	    devicefile="${line##*Device File: }"
	    devicefile=`echo $devicefile | cut -d" " -f1`
	    if [ "$mydevice" == "$devicefile" ]; then
		   found=1
		   break
	    fi
	    ;;
    esac
  done < /tmp/_FSTAB_HMC_/hwinfo.out
  rm /tmp/_FSTAB_HMC_/hwinfo.out
  return $found
}
trap "cleanup" 1 2 3 4 5 11 15
entry=`basename $1`
if [ "$entry" == "" ]; then
   exit 1
fi
if [ ! -d /tmp/_FSTAB_HMC_ ]; then
   mkdir /tmp/_FSTAB_HMC_
fi
UNIQUEID=""
option=$2
echo "Called with $* " >/tmp/hmcupdatefstab.log
if [ "$option" == "add" ]; then
    sleep 5
    for i in 1 2 3 4 5 6 7 8 9; do
       cat /proc/partitions | grep -q "$entry$i"
       if [ $? -eq 0 ]; then
          cleanup
       fi
    done
    if [ ! -f /media/$entry ]; then
         mkdir /media/$entry
    fi
    grep -q "^$1" /etc/fstab
    if [ $? -ne 0 ]; then
	findID $1
        if [ $? -eq 1 ]; then
          echo "$1    /media/$entry  auto     rw,sync,noauto,user,exec,owner 0 0    #HOTPLUG $UNIQUEID" >> /etc/fstab
	else
          echo "$1    /media/$entry  auto     rw,sync,noauto,user,exec,owner 0 0" >> /etc/fstab
	fi
	Beep
    else
        sed -e "/^\/dev\/$entry/d" /etc/fstab > /tmp/_FSTAB_HMC_/fstab.mod
	findID $1
        if [ $? -eq 1 ]; then
           echo "$1     /media/$entry  auto     rw,sync,noauto,user,exec,owner 0 0     #HOTPLUG $UNIQUEID" >> /tmp/_FSTAB_HMC_/fstab.mod
        else
           echo "$1     /media/$entry  auto     rw,sync,noauto,user,exec,owner 0 0" >> /tmp/_FSTAB_HMC_/fstab.mod
       fi
       mv /tmp/_FSTAB_HMC_/fstab.mod /etc/fstab
       Beep
    fi
fi
if [ "$option" == "remove" ]; then
      umount -l /media/$entry 2>/dev/null
      grep -q "^$1" /etc/fstab
      if [ $? -eq 0 ]; then
        sed -e "/^\/dev\/$entry/d" /etc/fstab > /tmp/_FSTAB_HMC_/fstab.mod
	if [ `filesize /tmp/_FSTAB_HMC_/fstab.mod` -ne 0 ]; then
           mv /tmp/_FSTAB_HMC_/fstab.mod /etc/fstab
	fi
      fi
      if [ -d /media/$entry ]; then
	 rmdir /media/$entry
      fi
fi
rm -rf /tmp/_FSTAB_HMC_
exit 0      
