#!/bin/bash
# mount local filesystems
#

#************************************************************
# Unmount the given media, and verify
# If unmount fails, terminate all processes with 
# file handles open to that media (first with SIGTERM, 
# and then SIGKILL if still running)
# Upon return of this function, the media is guaranteed to be
# unmounted.
# param: either /mnt/ide or /mnt/cf
unmount() {
  signal=TERM
  /bin/echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Unmounting $1..."
  /bin/umount $1 > /dev/null 2>&1
  mounted=`/bin/mount | /bin/grep -c $1`
  while [ $mounted -ne "0" ]
  do
    usedBy=`fuser -vum $1 | /bin/grep $1 | /bin/awk '// {print $2 ":" $5}'`
    message="failed because used by: $usedBy."
    /bin/echo $message
    /sbin/fuser -$signal -km $1
    /bin/sleep 1
    /bin/echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Retrying to unmount $1..."
    /bin/umount $1 > /dev/null 2>&1
    mounted=`/bin/mount | /bin/grep -c $1`
    signal=KILL    
  done
  echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Unmount success."
}
#***********************************************************

logs_link=/var/logs
logs_ram=/var/log
logs_ide=/mnt/ide/logs
logs_cf=/mnt/cf/logs

# Only sets log link if it is not already existing
set_logs() {
	if [ ! -d $1 ]; then
		echo "Creating " $1
		mkdir $1
	fi
	ln -s $1 ${logs_link} 2> /dev/null
}

set_store() {
	if [ ! -d $1 ]; then
		echo "Creating " $1
		mkdir $1
	fi
}



ls -l /var | /bin/grep -q "\-> ${logs_ram}"
is_ram_logs=$?

case $1 in

        start)
        echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Mounting local filesystems."
	
	if [ ${is_ram_logs} ]; then
		# Delete /var/logs soft link.  
		# The first drive to get mounted will create it 
		# In other words, IDE has priority to /var/logs
		rm ${logs_link}
	fi

        /bin/mount -t ext3 /dev/hda1 /mnt/ide
        if [ $? -eq 0 ] ; then
                # create symlinks
                set_logs ${logs_ide} 
		set_store /mnt/ide/store
        fi

        /usr/local/bin/fatfix -f /dev/hdc
	/bin/mount -t ext3 /dev/hdc1 /mnt/cf
        if [ $? -eq 0 ] ; then
                # create symlinks
                set_logs ${logs_cf} 
		set_store /mnt/cf/store
        fi

	# If IDE or CF failed to mount, re-link to ram logs
	# (ln -s will fail if the link already exists)
	set_logs ${logs_ram}

        ;;

        stop)
        echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Unmounting local filesystems."
        unmount /mnt/ide 
        unmount /mnt/cf
	if [ ! ${is_ram_logs} ]; then
		rm ${logs_link} 
		set_logs ${logs_ram}	
	fi
        
	;;

        *)
        echo $"usage: $0 start|stop";
        ;;
esac
