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

BASEDIR=/usr/local
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$BASEDIR/sbin:$BASEDIR/bin:$PATH
FSTAB="/etc/fstab.iscsi"
TIMEOUT=10
# 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 timeout=$TIMEOUT

        while [ $timeout -gt 0 ]; 
        do
                fsck $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 1 
                        timeout=$(($timeout - 1))
                        echo "*** probe failed, $timeout 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
}

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
        if try_fsck $dev ; then
            mount -t $fstype -o $options $dev $mountp
        fi
    fi
done < $FSTAB
