#!/bin/bash

#needs fstab entry like:
#//zoosecure/homes       /media/zoosecure_homes  cifs    users,noauto,noexec,credentials=/tmp/.cifs-creds        0       2       

if [ $# -eq 1 ] ; then
	SMBSHARE=$1;
else 
SMBSHARE=`zenity --width=400  --title="Mount Network Drive" --entry --text="Server Path"`
if [ $? = 1 ] ; then
        exit 0
fi
fi


SMBUSER=`zenity --width=400  --title="Mount Network Drive" --entry --text="Username for $SMBSHARE"`
if [ $? = 1 ] ; then 
	exit 0
fi

SMBPASSWD=`zenity --width=400   --title="Mount Network Drive" --entry --text=Password --hide-text`
if [ $? = 1 ] ; then 
	exit 0
fi
SMBSHARE_FNAME=`echo $SMBSHARE|  perl -pi -e 's/\/+$//;s/^\/+//;s/\/+/_/g' `
echo SMBSHARE_FNAME=$SMBSHARE_FNAME
#SMBMN=${SMBUSER}_on$SMBSHARE_FNAME
SMBMN=$SMBSHARE_FNAME
SMBLINK=$HOME/$SMBMN
SMBMNT=/media/$SMBMN

echo SMBSHARE_FNAME = $SMBSHARE_FNAME
echo SMBMN = $SMBMN
echo SMBMNT = $SMBMNT
echo SMBLINK = $SMBLINK

mkdir  $SMBMNT


#use the sudo method only if we can't have an fstab entry, this method also requires /etc/sudoers passwordless for [u]mount.cifs like this:
#	audio ALL = NOPASSWD:NOEXEC: /sbin/mount.cifs, /sbin/umount.cifs
##unmount first if necessary
#echo sudo umount.cifs  $SMBMNT
#     sudo umount.cifs  $SMBMNT
#
##mount it
#     echo "sudo mount.cifs $SMBSHARE $SMBMNT -o username=$SMBUSER%$SMBPASSWD,noexec "
#SMBSTATUS=`sudo mount.cifs $SMBSHARE $SMBMNT -o username=$SMBUSER%$SMBPASSWD,noexec 2>&1`

echo       umount $SMBMNT
           umount $SMBMNT
CCFILE=/tmp/.cifs-creds
rm -f $CCFILE
touch $CCFILE
chmod 700 $CCFILE
echo "username=$SMBUSER" >> $CCFILE
echo "password=$SMBPASSWD" >> $CCFILE
#echo      "mount $SMBMNT -o username=$SMBUSER%$SMBPASSWD"
#SMBSTATUS=`mount $SMBMNT -o username=$SMBUSER%$SMBPASSWD 2>&1`
echo      "mount $SMBMNT"
SMBSTATUS=`mount $SMBMNT 2>&1`
RS1=$?
echo $RS1
rm -f $CCFILE
#we look at the status from smbmount, but that is not always reliable: if the mount point cannot be created, smbmount still returns 0 (success) for some reason

#if we mounted correctly, the rmdir command should fail, so we use this as a more reliable measure for whether the mount was successful
# but that won't work with root owned mount point
#rmdir $SMBMNT
#RS2=$?
#echo $RS2

#RS=$RS2
RS=$RS1

if [ $RS -ne 0 ] ; then 
	zenity --width=400  --title="Mount Network Drive" --error --text="Access Denied.  Please double check your username and password and try again.\n\n$SMBSTATUS"
else
	#get rid of old, if exists and a directory we would create link inside leading to recursive links
	rm $SMBLINK
	echo ln -s $SMBMNT $SMBLINK
	     ln -s $SMBMNT $SMBLINK
	#can't write to home dir# ln -s $SMBMNT $SMBLINK

	#zenity --title="Mount Network Drive" --info --text="$SMBSHARE is now available at\n$SMBLINK and\n$SMBMNT"  &
	zenity --width=400  --title="Mount Network Drive" --info --text="$SMBSHARE is now available at\n$SMBLINK"  &
        thunar "$SMBLINK" &

	
fi
