#!/bin/bash

showHelp=0

valMnt=""

while [ "$1" != "" ]; do
	case "$1" in
	  -h | --help | --usage)
		showHelp="1"
		;;
	  --no-sudo )
		noSudo="1"
		;;
	  *)
		if [ "$valMnt" == "" ]; then
			valMnt="$1"
		fi
		;;
	esac
	shift
done

if [ "$showHelp" == "1" ]; then
	echo "Usage: umountnet [MOUNT_DIR]"
	echo "Disconnect partitions mounted from network by mountnet application"
	echo " "
	echo "Common options:"
	echo "  mount_dir   Target directory where is the remote directory mounted."
	echo " "
	echo "General options:"
	echo "  -h, --help, --usage  This help."
	echo "  --no-sudo            When root privileges are necessary, application forces"
	echo "                       sudo command. If you want to disable this feature, use"
	echo "                       this prefix."
	echo " "
	echo "(c) 2014-2019 LUnet Studio, http://LUnet.Studio"
	exit
fi


sc=""
if [ "$USER" != "root" ] && [ "$noSudo" != "1" ]; then
	sc="sudo "
	sudo echo "" > /dev/null
fi


if [ "$valMnt" == "" ]; then
	read -p "Umount target directory: " valMnt
fi
if [ "$valMnt" != "" ]; then
	${sc}umount $valMnt
	
	valLs=`ls $valMnt`
	if [ "$valLs" == "" ]; then
		${sc}rm -rf $valMnt
		echo "${valMnt} disconnected and cleaned."
	else
		echo "Umounting failed!"
		echo "${valMnt} is busy."
	fi
else
	echo "Required parameters was not specified."
	echo "Try 'umountnet --help' for more information."
fi
