#! /bin/sh
#
# Mount iSCSI devices listed in /etc/fstab

BASEDIR=/
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$BASEDIR/sbin:$BASEDIR/bin:$PATH
FSTAB="/etc/fstab.iscsi"
NUM_RETRIES=10
SLEEP_INTERVAL=1
# only show completion bar if stdout is a tty
if [ -t 1 ] ; then
    FSCK_OPTS="-C -a -T"
else
    FSCK_OPTS="-a -T"
fi    

if [ ! -f $FSTAB ]; then
        exit 1
fi;

try_fsck()
{
        local device=$1 retries=$NUM_RETRIES sleep_interval=$SLEEP_INTERVAL
	fstype=$2
	
        while [ $retries -gt 0 ]; 
        do
             fsck -t $fstype $FSCK_OPTS $device > /dev/null
             err=$?
                
             if [ $err -le 1 ]; then # fsck succeeded
                  return 0  
             elif [ $err -eq 8 ]; then # assume device not yet available
                   sleep $sleep_interval 
                   retries=$(($retries - 1))
                   echo "**device not yet available, $retries retries remaining"
             elif [ $err -ge 2 ]; then # fatal error
                   echo "*** automated fsck on $device failed" 
                   echo "*** repair manually with 'fsck $device'"
                   return 1
             fi
        done
        return 1
}

try_mount()
{
    local dev=$1
    local mountp=$2
    local fstype=$3
    local options=$4

    #
    # First check to see if the device entry in /etc/fstab.iscsi
    # matches anything in the mount output.  If it does, the
    # LUN is already mounted, and we don't need to fsck again.
    #
     for device in  `mount |grep "$dev"|awk '{print $1}'`;do
         if [ "$dev" = "$device" ];then
              return
         fi
     done

    #
    # The user could have specified a symbolic link.
    # If this is the case, the output from the mount command
    # may not match (it may contain the actual device, whereas
    # the user specified a link).  Thus, if it's
    # a symlink in the /etc/fstab.iscsi file, we need to
    # resolve the link and do an additional check.
    #
    if [ -L $dev ]; then
        lnname=`ls -l $dev | cut -d ">" -f 2 | cut -d " " -f 2`
        dev=$lnname
    fi

    for device in  `mount |grep "$dev"|awk '{print $1}'`;do
        if [ "$dev" = "$device" ];then
            return
        fi   
    done
    if try_fsck $dev $fstype ; then
	mount -t $fstype -o $options $dev $mountp
    fi 
}

while read dev mountp fstype options dummy1 dummy2
do
    case $dev 
    in
    \#*) continue ;; #  ignore comments
    '')  continue ;; # ignore empty lines
    esac

    if echo $options | grep -v -q noauto ; then
	try_mount $dev $mountp $fstype $options &
    fi
done < $FSTAB
