#!/bin/bash
# 2009-2010 (c) Etersoft http://etersoft.ru
# Author: Konstantin Baev <kipruss@etersoft.ru>
# GNU Public License

# Script for mount cifs shares with recommended mount options

fatal()
{
    echo "$@"
    exit 1
}

PACKAGEINFO=/usr/share/etercifs/package.conf
if [ -f "$PACKAGEINFO" ] ; then
  . $PACKAGEINFO
else
  fatal "Not found package information file $PACKAGEINFO"
fi

CONFIGFILE=/etc/sysconfig/etercifs.conf
if [ -f $CONFIGFILE ] ; then
  . $CONFIGFILE
else
  fatal "Not found configuration file $CONFIGFILE"
fi

# run via sudo under regular user
[ "$UID" = "0" ] && SUDO= || SUDO=sudo

create_share_dir()
{
    if [ -d "$1" ] ; then
        [ -n "`ls $1`" ] && fatal "Error: the folder $1 is not empty!"
        echo "Info: the folder $1 exists and empty"
    else
        if $(mkdir -p "$1") ; then
            echo "Info: the folder $1 was created"
        else
            fatal "Error while creating the folder $1"
        fi
    fi
}

help_text()
{
    echo "Package $MODULENAME version $MODULEVERSION"
    echo "The utility etermount performs mount network share on a protocol cifs"
    echo "with pre-set parameters, which determined in MOUNT_OPTIONS variable"
    echo "in the config file $CONFIGFILE"
    echo "(current value is '$MOUNT_OPTIONS')"
    echo
    echo "To mount the resource //server/share to the mountpoint /path/mountpoint"
    echo "need to execute the command (with root permissions):"
    echo
    echo "etermount <//server/share> [</path/mountpoint>]"
    echo
    echo "If the mountpoint isn't specified, will used"
    echo "variable DEFAULT_MOUNTPOINT from the config file $CONFIGFILE"
    echo "(current value is '$DEFAULT_MOUNTPOINT')."
    echo
    echo "Report bugs to <support@etersoft.ru>."
}

[ "$1" == '--help' -o "$1" == '-h' ] && { help_text ; exit 0 ; }

if [ -z "$*" ] ; then
    cat /proc/mounts | grep cifs
    exit
fi

# FIXME: Lav 19.02.10: I think, default mount path is useless
[ "$#" -ge 1 -a "$#" -le 2 ] || fatal 'Usage: etermount <//server/share> [</path/mountpoint>]. Use -h or --help options for help.'

if [ "$2" == '' ] ; then
    SHARE_PATH=$DEFAULT_MOUNTPOINT
else
    SHARE_PATH="$2"
fi

create_share_dir "$SHARE_PATH"

# we have samba-client requires in spec
if [ ! -x /sbin/mount.cifs ] ; then
	fatal "Please install package with /sbin/mount.cifs command (samba-client or smbfs)"
fi

echo "Mouting share $1 to $SHARE_PATH with $MOUNT_OPTIONS options..."
if $SUDO /sbin/mount.cifs "$1" "$SHARE_PATH" -o $MOUNT_OPTIONS ; then
    echo "Info: mount of share $1 in mountpoint $SHARE_PATH has been successfully"
else
    fatal "Warning: error while mount of share $1 in mountpoint $SHARE_PATH!"
fi
