#!/bin/bash
# title			: nasup
# description	: Detect and auto mount NAS (Network Attached Storage).
# author		: Glenn Cady <theemahn@ultimateedition.info>
# date			: 10/24/2013
# version		: 1.7.2-1
# usage			: nasup --help
# notes			: See change-log below for further information.
# bash_version	: 4.2.8(1)-release
# ==============================================================================
# Change-log:
# 1.7.1-5 		initial public release
# 1.7.1-6		Added net-mask detection, not all routers etc assign 192.168.1.*
# 1.7.1-7		Began implementation of NFS (Network File System)
#				Added reusable code in Version function
#				Added injection / auto-mounting of NFS to fstab
#				Added error handling routines to inform end user
# 1.7.1-8		Added auto-mount of NFS file-systems.
# 				Code cleanup using a tool I wrote.
#				Wrote bash auto completion handler.
#				Added active interface detection, should have been priority #1
# 1.7.2-1		Fixed help systems
#				Added report switch
#				Fixed bash auto-completion
#				Tossed wifi interfaces to the curb.
#				Bumped version # to comply with other tools being released.
#				Adjusted dependencies determined from bash-depends application
# 1.9.8			Added support for Western digital ™ MyCloud NAS
# 1.9.9 		Removed report switch as scan does the same thing.
#				Wrote a manual and PDF for the app.
# 2.0.0 		Arrayed detection for multiple NAS drives.
# 2.0.1 		Added scan routine to detect external drives on WD MyCloud.
# 2.0.2 		Added ability to "SHARE" a folder or Drive across Local Access Network (LAN).
# 2.0.3 		Fixed most RPC issues.
# 2.0.4 		Internal release
# 2.0.5 		Borrowed code from Uno (Ultimate Network Optimizer) for ACTIVE network detection.
#				Added GTK notifications
#				Set the app to load on boot up, detecting devices off the rip even off live disk.
#				Added interupt / kill support (CTRL - C) - trap exit smoothly.
#				Fixed Samba support.
#				Initial support for AFS (Apple File System)
# 2.0.7			Added Ultimate Arch Support
# 2.0.8			Added Qnap NAS Support
# 2.0.9			Added Wifi support.
# 2.1.2			Added detection and automount for nfs
# ==============================================================================
# Nasup(c) 2012 - 2026 Glenn Cady under GNU GPL v2.0+ by
# Glenn Cady <theemahn@ultimateedition.info> initially written explicitly for the
# ™ Seagate Go-flex line of NAS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
PASSWORD=''		# Your Password to mount the NAS - now prompts hiddenly
MOUNTPOINT='/media/NAS'	# Example: /media/NAS_3TB
NASIP=''		# Example: 192.168.0.105 not specifying an IP will search for the NAS
SLASH="/"		# Should not have to change this value

# You should not have to change any of the below. Actually none of the above as
# of 1.7.1-6 unless you would like to change the default mount-point.
# set colors so errors etc. stand out.
APPNAME="Nasup"
PROGNAME="nasup"
VERSION="2.1.2"
BUILDDATE="01/13/2026"
WEBSITE="os-builder.com"
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@${WEBSITE}>"

if [[ -f "ultimate-common" ]]; then
	source ultimate-common
elif [[ -f "/usr/share/ultimate_edition/ultimate-common" ]]; then
	source /usr/share/ultimate_edition/ultimate-common
else
	echo "No Ultimate Edition common source. Please install ultimate-edition-common."
fi

# Gloval Vars
declare -a EXTERNALLOCALIP=()
declare -a NASIPS=()
declare -a ISNAS=()
declare -i IPSDETECTED
declare -i array_counter
declare -i NDETECTED
declare -a IPBLOCK=()
declare -i NDRIVES
declare -i SAMBASHARES
declare -i AFP
SAMBASHARES=0
IPSDETECTED=0
NDRIVES=0
NDETECTED=0
NASTYPES=( "qnap" "seagate" "mycloud" );
NASLABEL=('Qnap NAS Drive(s).' ' Seagate NAS Drive(s)' 'Western Digital My cloud Drives')

ADD=$(echo "$@" | grep -i "add")
REMOVE=$(echo "$@" | grep -i "remove")
# Optional graphical notification, see if user has it installed.
NOTIFY=$(type -p notify-send)

# Optional Network Data
ETHTOOL=$(type -p ethtool)

# Set Standards
declare -a NETWORKTYPES=( 'nfs' 'afp' 'cifs' 'all' );
DEBUG=$(echo "$*" | grep -i "debug")

# Optional graphical notification, see if user has it installed.
NOTIFY=$(which notify-send)

# Optional sound notification, see if user has it installed.
SOUND=$(which canberra-gtk-play)

GrabOptions () {
	for OPTIONS in "$@"
	do
		for EACH in "${NETWORKTYPES[@]}"
		do
		if [[ "${DEBUG}" ]]; then
			echo "DEBUGGING: Scanning: $OPTIONS for ${EACH}"
		fi
		OPTION=$(echo "$*" | grep -i "$OPTIONS")
		if [[ "${DEBUG}" && "$OPTION" ]]; then
			echo "DEBUGGING: OPTION FOUND IN $@ setting scan for $OPTION."
		fi
		done
		#case "${EACH}";
		#	nfs) NFSSCAN "$@";;
		#	afp) AFPSCAN "$@";;
		#	cifs) CIFSSCAN "$@";;
		#	all | * ) NFSSCAN "$@";
		#				AFPSCAN "$@";
		#				CIFSSCAN "$@";;
		#esac
	done
}

RipTheInterNet () {
	# UNUSED Function
	for EACH in "$SUBLOCK"
	do
		a=$(ping "${EACH}")
		if [[ "$a" ]]; then
			Encapsulated "Host detected at: $a"
		fi
	done
}

NASType () {
	NASS=""
	INDEX=0
	for NASTYPE in "${NASTYPES[@]}"
	do
		CURRENT="${INDEX}"
		INDEX=$((INDEX + 1))
		PCOMP=$((100*INDEX / ${#NASTYPES[@]}))
		ProgressBar "${PCOMP}" "Scanning for ${NASLABEL[${CURRENT}]}: ${INDEX} of ${#NASTYPES[@]}"
		if ! [[ "${NASS}" ]]; then
			NASS=$(sudo nmap -O "${1}" | grep -i "${NASTYPE}")
			if [[ "${NASS}" ]]; then
				NASSTY="${NASTYPE}"
			fi
		fi
		case "${NASSTY}" in
			qnap) Encapsulate "QNAP NAS(s) detected."; break;;
			seagate) Encapsulate "Seagate NAS(s) detected."; break;;
			mycloud) Encapsulate "Western Digital My Cloud NAS(s) detected."; break ;;
			*) Encapsulate "Unknown NAS Attempting detection.";;
		esac
	done
}

RestartServices () {
	SERVICES=$(type -p "systemctl")
	Timer "Start" "RestartServices"
	if [[ "${1}" ]]; then
		VersionDump
	fi
	if [[ "${SERVICES}" ]]; then
		NFSSERVICE=$(systemctl status "nfs-server.service" | grep "enabled")
		if ! [[ "${NFSSERVICE}" ]]; then
			if [[ "${UID}" == "0" ]]; then
				Encapsulate "Enabling NFS Server service."
				systemctl enable nfs-server.service 1>/dev/null
			else
				Encapsulate "Enabling NFS Server service."
				sudo systemctl enable nfs-server.service 1>/dev/null
			fi
		else
			Encapsulate "NFS Server service is already enabled."
		fi
	fi
	if [[ "${UID}" == "0" ]]; then
		if [[ "${NFSSERVICE}" ]]; then
			Encapsulate "Restarting NFS Service."
			systemctl restart nfs-server.service
		else
			Encapsulate "No NFS Server service found. Install if you want that functionality."
		fi
	else
		if [[ "${NFSSERVICE}" ]]; then
			Encapsulate "Restarting NFS Service."
			sudo systemctl restart nfs-server.service
		else
			Encapsulate "No NFS Server service found. Install if you want that functionality."
		fi
	fi

	if [[ "${SERVICES}" ]]; then
		SAMBASERVICE=$(systemctl status "samba.service" | grep "enabled")
		if ! [[ "${SAMBASERVICE}" ]]; then
			if [[ "${UID}" == "0" ]]; then
				Encapsulate "Enabling Samba Server service."
				systemctl enable samba.service 1>/dev/null
			else
				Encapsulate "Enabling Samba Server service."
				sudo systemctl enable samba.service 1>/dev/null
			fi
		else
			Encapsulate "Samba Server service is already enabled."
		fi
	fi
	if [[ -f "/etc/init.d/smbd" ]]; then
		Encapsulate "Restarting Samba Initd Services."
		if [[ "${UID}" == "0" ]]; then
			/etc/init.d/smbd restart 1>/dev/null
		else
			sudo /etc/init.d/smbd restart 1>/dev/null
		fi
	fi
	if [[ "${SERVICES}" ]]; then
		if [[ "${UID}" == "0" ]]; then
			if [[ "${SAMBASERVICE}" ]]; then
				Encapsulate "Restarting Samba Service."
				systemctl restart samba.service
			else
				Encapsulate "No Samba Server service found. Install if you want that functionality."
			fi
		else
			if [[ "${SAMBASERVICE}" ]]; then
				Encapsulate "Restarting Samba Service."
				sudo systemctl restart samba.service
			else
				Encapsulate "No Samba Server service found. Install if you want that functionality."
			fi
		fi
	fi

	if [[ "${1}" ]]; then
		Timer "Stop" "RestartServices"
		FullBar
		exit 0;
	fi
}

SetSambaInterface () {
	declare -i CHANGE
	ACTIVEINTERFACE="${1}"
	if ! [[ "${ISARCH}" ]]; then
		ISSAMBAINSTALLED=$(dpkg -l | grep "samba")
	else
		ISSAMBAINSTALLED=$(pacman -Qs "samba")
	fi
	if ! [[ "${ISSAMBAINSTALLED}" ]]; then
		if ! [[ "${ISARCH}" ]]; then
			Error "Samba is not installed apt-get install samba if you want Samba functionality."
		else
			Error "Samba is not installed sudo pacman -Syuu samba if you want Samba functionality."
		fi
	fi
	if [[ "${ACTIVEINTERFACE}" ]]; then
		if [[ -f "/etc/samba/smb.conf" ]]; then
			GREPIT=$(grep -i "${ACTIVEINTERFACE}" /etc/samba/smb.conf)
			if [[ "${GREPIT}" ]]; then
				Encapsulate "Samba Interface has already been set."
			else
				CHANGE=1
				Encapsulate "Setting Samba Interface as ${1}"
				#TESTING=$(echo "${SHAREFOLDER}	*(rw,sync,no_subtree_check)" | tee -a /etc/exports 2>/dev/null)
				if [[ "${UID}" == "0" ]]; then
					TESTING=$(echo "interfaces = 127.0.0.0/8 ${ACTIVEINTERFACE}" | tee -a /etc/samba/smb.conf > /dev/null)
				else
					TESTING=$(echo "interfaces = 127.0.0.0/8 ${ACTIVEINTERFACE}" | sudo tee -a /etc/samba/smb.conf > /dev/null)
				fi
			fi
			GREPIT=$(grep -i "server string =" /etc/samba/smb.conf | grep -i "Ultimate")
			if [[ "${GREPIT}" ]]; then
				Encapsulate "Server String has already been set."
			else
				CHANGE=1
				Encapsulate "Setting Server string as Ultimate Edition"
				sed "/server\ string\ =/d" /etc/samba/smb.conf
				if [[ "${UID}" == "0" ]]; then
					TESTING=$(echo "server string = %h server (Samba, Ultimate Edition)" | tee -a /etc/samba/smb.conf > /dev/null )
				else
					TESTING=$(echo "server string = %h server (Samba, Ultimate Edition)" | sudo tee -a /etc/samba/smb.conf > /dev/null )
				fi
			fi
			if [[ "${CHANGE}" == "1" ]]; then
				RestartServices
			fi
		fi
	else
		Error "No interface specified."
	fi
}

NetInfo () {
	#Advance network detection to perfection scan all interfaces:
	shopt -s nullglob
	declare -a INTERFACES=()

	ACTIVE=""
	BYTE=0
	if [[ -d "/sys/class/net/" ]]; then
		Columnize -t "INTERFACE" "STATUS" "SPEED" "DUPLEX" "TYPE"
		FullBar
		CURRENT="${PWD}"
		cd "/sys/class/net/" || exit 1;
		INTERFACES=(*/)
		for EACH in "${INTERFACES[@]}"
		do
			ACT=$(cat "/sys/class/net/${EACH%/}/operstate")
			if [[ "$ACT" == "up" ]]; then
					DEVICE="${EACH%/}"
					#ACTIVE="${EACH%/}"
					DUPLEX=$(ethtool "${DEVICE}" 2>/dev/null | grep -s -i "Duplex" | cut -d ":" -f2 | sed 's/ //g') 2>/dev/null
					ITYPE=$(ethtool "${DEVICE}" 2>/dev/null | grep -s "Port" | cut -d ":" -f2 | cut -d " " -f2) 2>/dev/null
					SPEED=$(ethtool "${DEVICE}" 2>/dev/null | grep -s -i "Speed" | cut -d ":" -f2 | sed 's/ //g') 2>/dev/null
					BYTES=$(ethtool --statistics "${DEVICE}" 2> /dev/null | grep -i "rxq0: rx_bytes:" | cut -d ":" -f3 | sed "s/ //g")
					if [[ "${BYTES}" == "" ]]; then
						if [[ -f "/sys/class/net/${DEVICE}/statistics/rx_bytes" ]]; then
							BYTES=$(cat "/sys/class/net/${DEVICE}/statistics/rx_bytes")
							SPEED=$(ethtool "${DEVICE}" 2>/dev/null | grep -s -i "Speed" | cut -d ":" -f2 | sed 's/ //g') 2>/dev/null
						fi
					fi
					if [[ "${BYTES}" -gt "${BYTE}" ]]; then
						ACTIVE="${EACH%/}"
						BYTE="${BYTES}"
					fi
				if ! [[ "${SPEED}" ]]; then
					SPEED=$(iwconfig ${EACH%/} | grep "Bit Rate=" | cut -d "=" -f2 | cut -d " " -f1,2)
					ITYPE="Wireless"
					DUPLEX=$(iwconfig ${EACH%/} | grep "Frequency:" | cut -d ":" -f2 | cut -d " " -f1,2)
				fi
				Columnize "${EACH%/}" "UP" "${SPEED}" "${DUPLEX}" "${ITYPE}"
				#Encapsulate "Interface: ${EACH%/} is $ACT"
			else
				#Encapsulate "Interface: ${EACH%/} is $ACT"
				if [[ "${EACH%/}" != "lo" ]]; then
					Columnize "${EACH%/}" "DOWN" "N/A" "N/A" "N/A"
				fi
			fi
		done
	else
		Error "No standard interface detected.	Point to Point Protocol?"
	fi
	# Current Seedo work...  If the folder exists most likely it is the
	# active connection set it as such.  Point to Point Protocol evidently
	# does not do states. up / down etc.
	if [[ -d "/sys/class/net/ppp0/" && "${ACTIVE}" == "" ]]; then
		ACTIVE="ppp0"
	fi
	if [[ "${ACTIVE}" ]]; then
		FullBar
		Encapsulate "Active Monitoring Connection:"
		if [[ "${ETHTOOL}" ]]; then
			SPEED=$(ethtool "${ACTIVE}" 2>/dev/null | grep -s -i "Speed" | cut -d ":" -f2 | sed 's/ //g') 2>/dev/null
		fi
		if [[ "${SPEED}" ]]; then
			Encapsulate "${ACTIVE} (Network Speed: ${SPEED})"
		else
			WLIST=$(type -p iwlist)
			if [[ "${WLIST}" ]]; then
				SPEED=$(iwlist "${ACTIVE}" bitrate | grep -i "bit rate" | cut -d "=" -f2)
				Encapsulate "${ACTIVE} (Network Speed: ${SPEED})"
			fi
		fi
	else
		Error "No active network interface found."
	fi
	FullBar
	#Notification "Active networking interface: ${ACTIVE} Speed: ${SPEED}."
	SetSambaInterface "${ACTIVE}"
	FullBar
}

IsLocalIP () {
	IP="${1}"
	LOCALHST=0
	INFOLDER="${PWD}"
	SAVEIFS=${IFS}
	# Change IFS to new line.
	IFS=$'\n'
	EXTERNALLOCALIP=$(ip addr | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1')
	EXTERNALLOCALIP=($EXTERNALLOCALIP)
	for IPS in "${EXTERNALLOCALIP[@]}"
	do
	if [[ "${IPS}" == "${IP}" ]]; then
			Encapsulate "$IPS is a local host, not adding to /etc/fstab."
			LOCALHST=1
	fi
	if [[ "${DEBUG}" ]]; then
		echo "Debugging $IPS: AGAINST: ${1} | LOCALHST=${LOCALHST}"
	fi
	done
	IFS="${SAVEIFS}"
	#cd "${INFOLDER}" || exit 1;
}

Interface () {
	#Advance network detection to perfection scan all interfaces:
	#Code borrowed from Conky Builder ;) I love it when previous software
	#I wrote suits my current needs.
	INFOLDER="${PWD}"
	if [[ -d "/sys/class/net/" ]]; then
		cd "/sys/class/net/" || exit 1;
	fi
	#shopt -s nullglob
	declare -a INTERFACES=();
	declare -i NIFACES
	INTERFACES=(*)
	NIFACES="${#INTERFACES[@]}"
	# find active network.
	#if [[ "$NIFACES" -gt 0 ]]; then
	#	Encapsulate "Number of interface(s) detected: $NIFACES"
	#	for EACH in "${INTERFACES[@]}"
	#	do
	#		Encapsulate "Scanning ${EACH} to see if it is active."
	#		ACT=$(cat "/sys/class/net/${EACH}/operstate")
	#		if [[ "$ACT" == "up" ]]; then
	#			ISWIFI=$(echo "${EACH}" | grep "wlan")
	#			if [[ "$ISWIFI" ]]; then
	#				Encapsulate "${EACH} is wifi, not setting active."
	#			else
	#				Encapsulate "Setting ${EACH} as active network connection."
	#				ACTIVE="${EACH}"
	#				#echo $FILE > /tmp/tmpo.txt
	#			fi
	#		fi
	#	done
	#fi
#	ls /sys/class/net/ > /tmp/ifaces.txt
#	if test -f /tmp/ifaces.txt
#		then
#		Encapsulate "Network interfaces detected"
#		cat /tmp/ifaces.txt
#		Encapsulate "Scanning for active"
#		cat /tmp/ifaces.txt | while read FILE
#		do
#			target=$(echo "$FILE" | sed -e "s/ /_/")
#			echo -n "Interface $FILE: "
#			ACT=$(cat /sys/class/net/$FILE/operstate)
#			echo $ACT
#			if [[ $ACT == 'up' ]]; then
#				ISWIFI=$(echo $FILE | grep 'wlan')
#				if [[ $ISWIFI ]]; then
#					echo "$FILE is wifi, not setting active."
#				else
#					ACTIVE=$FILE
#					echo $FILE > /tmp/tmpo.txt
#				fi
#			fi
#			# Inform end user of our findings or lack there of.
#			if [[ ${ACTIVE} ]]; then
#				Encapsulate "Active Network So far: "${ACTIVE}
#			else
#				Encapsulate "Unable to determine active network, exiting."
#				exit 0
#			fi
#		done

		# Current Seedo work...	If the folder exists most likely it is the
		# active connection set it as such.	Point to Point Protocol evidently
		# does not do states. up / down etc.

		if [[ -d "/sys/class/net/ppp0/" && ${ACTIVE} == "" ]]; then
			ACTIVE="ppp0"
			Encapsulate "Point to point protocol detected, setting active."
		fi
#	else
#		echo 'No Active network.'
#	fi
#	if test -f /tmp/tmpo.txt
#		then
#		ACTIVE=$(cat /tmp/tmpo.txt)
#	else
#		ACTIVE=''
#	fi
#	if test -f /tmp/tmpo.txt
#		then
#		WIRELESS=$(cat /tmp/tmpo.txt|grep 'wlan')
#	fi
#	if [[ $WIRELESS != '' ]]
#		then
#		wlan='up'
#	fi

	#Clean up.
#	if test -f /tmp/ifaces.txt
#		then
#		rm /tmp/ifaces.txt
#	fi
#	if test -f /tmp/tmpo.txt
#		then
#		rm /tmp/tmpo.txt
#	fi
	cd "${INFOLDER}" || exit 1;
	IPBLOCK=$(ifconfig | grep "${ACTIVE}" -A5 | grep 'inet ' | awk '{print $2};' | cut -f 1-3 -d. | cut -d ":" -f2)
}

Conclude () {
	# Define & report how many NAS drive(s) were detected.
	Encapsulate "Syncronising."
	sync
	TOTALNAS=$((${SAMBASHARES} + ${NDETECTED}))
	if [[ "${TOTALNAS}" != 0 ]]; then
		Encapsulate "Mounting ${TOTALNAS} NAS drive(s)."
		sudo mount -a 2>/dev/null
	fi
	SYSTEMD=$(type -p systemd)
	if [[ "${SYSTEMD}" ]]; then
		Encapsulate "Reloading Systemd."
		sudo systemctl daemon-reload 2>/dev/null
	fi
	NDRIVES="${#NASIPS[@]}"
	if [[ "${NDRIVES}" -gt "0" ]]; then
		Notification "Server(s) / IP (s) detected: ${IPSDETECTED} | ${SAMBASHARES} Samba Share(s) | ${NDETECTED} NFS NAS Drive(s) detected. Total Drives mounted: ${TOTALNAS} | Active networking interface: ${ACTIVE} Speed:${SPEED}"
	fi
	FullBar
	exit 0;
}

ScanDevices () {
	# Scan Active IP Block
	SAVEIFS=${IFS}
	IPADDRESSES=();
	NASIPS=();
	IFS=$'\n'
	IPADDRESSES=$(arp -a | cut -d "(" -f2 | cut -d ")" -f1) & Spinner "Scanning your entire network, please wait."
	IPADDRESSES=($IPADDRESSES)
	IFS="${SAVEIFS}"
	IPSDETECTED="${#IPADDRESSES}"
	NASIPS=("${IPADDRESSES[@]}")
	# Begin Scan for NAS drive(s)
	#Encapsulate "Scanning ${IPBLOCK}.* for Seagate Go-flex NAS on ${IPBLOCK}.*, please wait."
	CIFS="${IFS}"
	#IFS='\n' read -r -a NASIPS <<< "$TEMPS"
	#shopt -s nullglob

	FOLDER="NAS"
	#NASIP=$(nmap --system-dns -sP "${IPBLOCK}.0/24" | awk /report/ | grep -i "GoFlex" | cut -f2 -d"(" | sed "s/)//g")
	#IFS=$'\n'
	NASIPS=$(nmap --system-dns -sn "${IPBLOCK}.0/24" | grep -i "Nmap scan report for" | sed "s/Nmap scan report for //g" | cut -d "(" -f2 | sed "s/)//g" | sed "s/ //g")
	IFS=$'\n' y=(${NASIPS})
	IPSDETECTED=$(echo "${NASIPS}" | wc -l)
	#y=("${NASIPS[@]}")
	Encapsulate "Number of IP's detected on the network: ${IPSDETECTED} device(s)"
}

ScanExternals () {
	Encapsulate "Scanning for external drive on ${1}"
	declare -a EXTERNALS=();
	INFOLDER="${PWD}"
	#shopt nullglob
	if [[ -d "${1}" ]]; then
		cd "${1}" || exit 1;
		EXTERNALS=(*)
		for EACH in "${EXTERNALS[@]}"
		do
			Encapsulate "FOUND: ${EACH}"
		done
	else
		Encapsulate "Folder ${1} does not exist exiting."
		exit 1;
	fi

	for EACH in "${EXTERNALS[@]}"
	do
		echo "DEBUGGING EACH: ${EACH}"
	done
}

ScanSamba () {
	#IFS=$'\n' y=(${NASIPS})
	#NDRIVES=(${#y[@]})
	declare -a SHARES=()
	declare -i CDRIVE
	CDRIVE=1
	# Whoopsie no NAS found
	if [[ "${NASIPS[@]}" == "" ]];then
		Error "Error: Unable to determine Samba IP address. Please manually provide IP. man ${PROGNAME} for more info."
		exit 1;
	fi
	INDEX=0
	for EACH in "${y[@]}"
	do
		LOCALHST=0
		ISNAS=""
		CURRENT="${INDEX}"
		INDEX=$((INDEX + 1))
		PCOMP=$((100*INDEX / ${#y[@]}))
		ProgressBar "${PCOMP}" "Scanning IP ${EACH}: ${INDEX} of ${#y[@]}"
		ISUP=$(nmap -p445 --script smb-protocols "${EACH}" | grep "smb-protocols")
		if [[ "${ISUP}" ]]; then
			NASType "${EACH}"
			# if NFS switch is implemented set default mount-points as such.
			MOUNTPOINT="/media/SAMBA${CDRIVE}/"
			SAMBASHARES=$(( SAMBASHARES + 1 ))
			GREPIT=$(grep -i "${MOUNTPOINT}" "/etc/fstab")
			if [[ "${DEBUG}" ]]; then
				echo "DEBUGGING GREPIT:${GREPIT}"
			fi
			if [[ "${REMOVE}" ]]; then
				if [[ "${GREPIT}" ]]; then
					Encapsulate "Removing mountpoint: ${MOUNTPOINT}"
					sed "/${MOUNTPOINT}/,$!d" /etc/fstab
					SHORT=$(basename "${MOUNTPOINT}")
					GREPIT=$(grep -i "${SHORT}" "/etc/samba/smb.conf")
					if [[ "${GREPIT}" ]]; then
						Encapsulate "Removing [${SHORT}] section from Samba Shares."
						sed -e "/${SHORT}/,+6d" /etc/samba/smb.conf
						if [[ -d "${MOUNTPOINT}" ]]; then
							umount -a
							find "${MOUNTPOINT}" -type d -empty -delete
						fi
					else
						Encapsulate "[${SHORT}] section not found in samba shares."
					fi
				else
					Encapsulate "Mountpoint: ${MOUNTPOINT} does not exist. Nothing to remove."
				fi
			fi
			if [[ "${ADD}" ]]; then
				CheckRoot "$@"
				GREPIT=$(grep -i "${MOUNTPOINT}" "/etc/fstab")
				if ! [[ "${GREPIT}" ]]; then
					#Encapsulate "Adding mountpoint: ${MOUNTPOINT}"
					IsLocalIP "${EACH}"
					if [[ "${DEBUG}" ]]; then
						echo "DEBUGGING NDETECTED:${NDETECTED} MOUNTPOINT:${MOUNTPOINT} LOCALHST:${LOCALHST}"
					fi
					if [[ "${LOCALHST}" == 0 ]]; then
						SHARES=$(smbclient -N -L "${EACH}" | grep -iEv 'IPC|PRINT' | grep "Disk" | awk '{print $1}')
						IFS=$'\n' ALLSHARES=($SHARES)
						if [[ "${DEBUG}" ]]; then
							echo "DEBUGGING SHARES:${SHARES} ALLSHARES:${ALLSHARES} LOCALHST:${LOCALHST}"
						fi
						for TSHARES in "${ALLSHARES[@]}"
						do
							MOUNTPOINT="/media/SAMBA${CDRIVE}/"
							Encapsulate "Adding found share: ${TSHARES} from IP: ${EACH} Setting mountpoint to: ${MOUNTPOINT}"
							mkdir -p "${MOUNTPOINT}"
							Encapsulate "Chowning folder: ${MOUNTPOINT} to ${IUSER}"
							sync
							if [[ "${UID}" == "0" ]]; then
								chown "${IUSER}:${IUSER}" "${MOUNTPOINT}" > /dev/null 2>&1 || Error "Error: Can not chown ${MOUNTPOINT} to ${IUSER}";
								chmod 777 -R "${MOUNTPOINT}" > /dev/null 2>&1 || Error "Error: Can not chmod ${MOUNTPOINT}.";
							else
								sudo chown "${IUSER}:${IUSER}" "${MOUNTPOINT}" > /dev/null 2>&1 || Error "Error: Can not chown ${MOUNTPOINT} to ${IUSER}";
								sudo chmod 777 -R "${MOUNTPOINT}" > /dev/null 2>&1 || Error "Error: Can not chmod ${MOUNTPOINT}.";
							fi
							Encapsulate "Setting /etc/fstab entry for ${MOUNTPOINT}"
							if [[ "${UID}" == "0" ]]; then
								echo '\\'"${EACH}"'\'"${TSHARES} ${MOUNTPOINT} cifs guest,iocharset=utf8,vers=3.0,noperm 0 0" | tee -a /etc/fstab > /dev/null 2>&1 || Error "Error: Can not set fstab entry.";
								Encapsulate "Mounting: ${MOUNTPOINT}"
								mount "${MOUNTPOINT}"
							else
								echo '\\'"${EACH}"'\'"${TSHARES} ${MOUNTPOINT} cifs guest,iocharset=utf8,vers=3.0,noperm 0 0" | sudo tee -a /etc/fstab > /dev/null 2>&1 || Error "Error: Can not set fstab entry.";
								Encapsulate "Mounting: ${MOUNTPOINT}"
								sudo mount "${MOUNTPOINT}"
							fi
							CDRIVE=$(( CDRIVE +1 ))
							SHORT=$(basename "${MOUNTPOINT}")
							GREPITAGAIN=$(grep -i "${SHORT}" "/etc/samba/smb.conf")
							if ! [[ "${GREPITAGAIN}" ]]; then
								Encapsulate "Adding [${SHORT}] section from Samba Shares to config."
								if [[ "${UID}" == "0" ]]; then
									TESTING=$(echo "[${SHORT}]" | tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "comment = Entry added via Nasup" | tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "path = ${MOUNTPOINT}" | tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "browseable = yes" | tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "read only = no" | tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "guest ok = yes" | tee -a /etc/samba/smb.conf 2>/dev/null)
								else
									TESTING=$(echo "[${SHORT}]" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "comment = Entry added via Nasup" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "path = ${MOUNTPOINT}" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "browseable = yes" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "read only = no" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
									TESTING=$(echo "guest ok = yes" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
								fi
							else
								Encapsulate "[${SHORT}] section not found in samba shares."
							fi
						done
					fi
				else
					Encapsulate "Mountpoint: ${MOUNTPOINT} exists. Nothing to add."
				fi
			fi
		fi
	done
	# Define & report how many NAS drive(s) were detected.
	NDRIVES=$(echo "${NASIPS}" | wc -l)
	Encapsulate "${SAMBASHARES} Samba Share(s) detected."
	FullBar
}

ScanNFS () {
	Encapsulate "Scanning for NFS (Network File System) based devices, please wait."
	# -->Additional scanning code will go here for freenas, netgear etc.<--
	INDEX=0
	for EACH in "${y[@]}"
	do
		LOCALHST=0
		ISNAS=""
		CURRENT="${INDEX}"
		INDEX=$((INDEX + 1))
		PCOMP=$((100*INDEX / ${#y[@]}))
		ProgressBar "${PCOMP}" "Scanning IP ${EACH}: ${INDEX} of ${#y[@]}"
		#Encapsulate "Scanning ${EACH} for NFS mounts."
		if [[ "${DEBUG}" ]]; then
			echo -n "DEBUGGING EACH: ${EACH}"
			showmount -e ${EACH} | sed -n '1!p'
		fi
		IsLocalIP "${EACH}"
		if [[ "${LOCALHST}" == 0 ]] ; then
			if [[ "${UID}" == 0 ]]; then
				ISNAS=$( nmap -sU -p 111 "${EACH}" | grep "open" | grep -v "filtered" 2>/dev/null)
			else
				ISNAS=$( sudo nmap -sU -p 111 "${EACH}" | grep "open" | grep -v "filtered" 2>/dev/null)
			fi
		fi
		if [[ "${ISNAS}" ]]; then
			ISNAS=$(showmount -e "${EACH}" | sed -n '1!p' | cut -d " " -f1 2>/dev/null)
		fi
		#IFS=$'\n' z=($ISNAS)
		array_counter=0
		IFS=$'\n' z=($ISNAS)
		if ! [[ "${z[@]}" == "" ]]; then
			if [[ "${DEBUG}" ]]; then
				echo "DEBUGGING: z[@]:${z[@]}"
				echo "DEBUGGING ARRAY ELEMENT 0 z[0]:${z[0]}"
			fi
			array_counter=0
			if [[ "${LOCALHST}" == 0 ]] ; then
				Encapsulate "NAS(s)found, on IP: ${EACH}. Detecting type.  Please wait."
				#NASType "${EACH}"
				Encapsulate "${EACH} has the following mount points:"
			fi
			for MOUNTPOINTS in "${z[@]}"
			do
				array_counter=$((array_counter + 1))
				MOUNTPOINT=$(echo "${MOUNTPOINTS}" | cut -d " " -f1)
				if [[ "$array_counter" ]]; then
					NDETECTED=$((NDETECTED + 1))
					#IsLocalIP "${EACH}"
					if [[ "${DEBUG}" ]]; then
						echo "DEBUGGING NDETECTED:${NDETECTED} FOLDER:${FOLDER} LOCALHST:${LOCALHST}"
					fi
					if ! [[ "${LOCALHST}" == 0 ]]; then
						Error "${EACH} is mounted on local host, not adding."
						#break;
					else
						if [[ "${MOUNTPOINTS}" ]]; then
							CMOUNT="/${MOUNTPOINTS/\//}"
							LMOUNT="${CMOUNT}"
						else
							CMOUNT="${FOLDER}${NDETECTED}/"
							LMOUNT="${FOLDER}${NDETECTED}/"
						fi
						if ! [[ -d "${CMOUNT}" ]]; then
							sudo mkdir -p "${CMOUNT}" 2>/dev/null || Error "Error: Can not mkdir ${LMOUNT}."
							sudo chown -R ${IUSER}:${IUSER} "${CMOUNT}" 2>/dev/null|| Error "Error: Can not chown to user ${IUSER}."
							LMOUNT="${CMOUNT}"
						fi
						GREPIT=$(grep -i "${LMOUNT}" "/etc/fstab")
						if ! [[ "${GREPIT}" ]]; then
								if [[ "${ADD}" ]]; then
									CheckRoot "$@"
									Encapsulate "Mountpoint on IP: ${EACH} detected as ${MOUNTPOINTS}, setting as ${LMOUNT}"
								if ! [[ -d "${LMOUNT}" ]]; then
										sudo mkdir -p "${LMOUNT}"
									Encapsulate "Chowning folder: ${LMOUNT} to ${IUSER}"
									if [[ "${UID}" == "0" ]]; then
										chown "${IUSER}:${IUSER}" "${LMOUNT}" > /dev/null 2>&1 || Error "Error: Can not chown ${LMOUNT} to ${IUSER}";
										chmod 777 -R "${LMOUNT}" > /dev/null 2>&1 || Error "Error: Can not chmod ${LMOUNT}.";
									else
										sudo chown "${IUSER}:${IUSER}" "${LMOUNT}" > /dev/null 2>&1 || Error "Error: Can not chown ${LMOUNT} to ${IUSER}";
										sudo chmod 777 -R "${LMOUNT}" > /dev/null 2>&1 || Error "Error: Can not chmod ${LMOUNT}.";
									fi
								fi
									GREPIT=$(grep -i "${EACH}:${MOUNTPOINTS}		${LMOUNT}		nfs		rsize=8192,wsize=8192,timeo=14,_netdev	 0 0" "/etc/fstab")
									if ! [[ "${GREPIT}" ]]; then
										if [[ "${UUID}" == "0" ]]; then
											Encapsulate "Not doing squat other then reporting."
										else
											Encapsulate "Setting /etc/fstab entry for ${LMOUNT}"
											INJECT=$(echo "${EACH}:${MOUNTPOINTS}		${LMOUNT}		nfs		rsize=8192,wsize=8192,timeo=14,_netdev	 0 0" | sudo tee -a /etc/fstab 2>/dev/null)
										fi
									else
										Error "${LMOUNT} entry exists in the /etc/fstab. Not adding."
									fi
							else
								Error "${PROGNAME} is in scan mode ${LMOUNT} found. Not adding to fstab."
							fi
						else
							Encapsulate "Mountpoint on IP: ${EACH} detected as ${MOUNTPOINTS}, is already set as ${LMOUNT}"
						fi
					fi
					if [[ "${REMOVE}" ]]; then
						CheckRoot "$@"
						GREPIT=$(grep -i "${FOLDER}${NDETECTED}" "/etc/fstab")
						ISMOUNTED=$(mount | grep -i "${FOLDER}${NDETECTED}")
						if [[ "$ISMOUNTED" ]]; then
							Encapsulate "Unmounting: ${FOLDER}${NDETECTED}"
							umount -l "${LMOUNT}"
						fi
						if [[ "${GREPIT}" ]]; then
							Encapsulate "Removing mountpoint: ${LMOUNT} from /etc/fstab."
						sed -i "/${FOLDER}${NDETECTED}/d" /etc/fstab
					else
						Encapsulate "${FOLDER}${NDETECTED} is not in the /etc/fstab, not doing anything."
					fi
					if [[ -d "${LMOUNT}" ]]; then
						Encapsulate "Folder: ${LMOUNT} exists, erasing if empty."
						find "${LMOUNT}" -type d -empty -delete
					fi
				fi
				if ! [[ "${ADD}" || "${REMOVE}" ]]; then
					LMOUNT="/media/${FOLDER}${NDETECTED}/"
					GREPIT=$(grep -i "${LMOUNT}" "/etc/fstab")
					if [[ "${GREPIT}" ]]; then
						Encapsulate "NFS entry in /etc/fstab for ${LMOUNT} has already been set."
					else
						Encapsulate "Detected mount point at ${LMOUNT} not doing anything but reporting man nasup if you want to add entry."
					fi
				fi
			fi
		done
		fi
	done
	IFS="$CIFS"
	#echo "USER:		${USER}"
	#echo "SUDO_USER: ${SUDO_USER}"
	#for EACH in /media/NAS*; do chown -R ${USER}:${USER} "${EACH}"; done
}

Scan () {
	# Initiate header
	VersionDump
	ADD=$(echo "$@" | grep -i "add")
	REMOVE=$(echo "$@" | grep -i "remove")
	if [[ "${ADD}" ]]; then
		CheckRoot "$@"
	fi
	if [[ "${REMOVE}" ]]; then
		CheckRoot "$@"
	fi
	Timer "Start" "Scan"
	# Scan for active interface
	NetInfo "$@"
	Interface "$@"
	# Command switch check for NFS
	NFS=$(echo "$@" | grep -i "nfs")
	# Command switch check for Samba
	SMB=$(echo "$@" | grep -i "smb\|samba")
	# ALL Networking...
	ALL=$(echo "$@" | grep -i "all")
	# Determine number of devices on the network
	ScanDevices "$@"
	# Process acclible switches
	# Did the user request scanning for NFS (Network File System) Devices or all devices?
	# We will eventually set all as default.
	if [[ "$NFS" || "${ALL}" ]];then
		ScanNFS "$@"
	fi
	# Did the user request scanning for Samba (SMB/CIFS protoco) Devices or all devices?
	if [[ "${SMB}" || "${ALL}" ]];then
		ScanSamba "$@"
	fi
	Conclude "$@"
	# Stop the timer and display how long it took.
	Timer "Stop" "Scan"
}

# Currently unimplemented code.
MountNAS () {
	echo "mount -t cifs '//'${1}'/GoFlex Home Personal' $4 -o username=${2},password=$3,iocharset=utf8,file_mode=0777,dir_mode=0777"
	mount -t cifs "//'${1}'/GoFlex Home Personal $4 -o username=${2},password=$3,iocharset=utf8,file_mode=0777,dir_mode=0777"
}

Help () {
	if [[ ${2} == "" ]];then
		PRAM="ALL"
	else
		PRAM="${2}"
	fi

	VersionDump "$@"
	case "$PRAM" in
		ALL)
		Encapsulate "Usage: ${PROGNAME} -<-COMMAND> [OPTION]"
		FullBar
		Encapsulate "Mandatory arguments to long options are identical for short options."
		Encapsulate "  possible commands..."
		Encapsulate " "
		Encapsulate "  -d   --disable   disable nasup service"
		Encapsulate "  -e   --enable    enable nasup service"
		Encapsulate "  -h   --help      this help message"
		Encapsulate "  -i   --info      dispays info about nastype"
		Encapsulate "  -r   --restart   restarts network services on local network."
		Encapsulate "  -s   --scan      scans for NAS drive on network."
		Encapsulate "  -S   --share     share folder / drive on LAN."
		Encapsulate "  -v   --version   dump version info and exit."
		Encapsulate " "
		FullBar
		Center "${PROGNAME} --help [COMMAND] for further information."
		FullBar;;
		ALL|h|help)
		Encapsulate "Usage help;"
		Encapsulate "nasup -h [COMMAND]"
		Encapsulate "Display help for [COMMAND]"
		Encapsulate "  possible commands..."
		Encapsulate " "
		Encapsulate "  -d   --disable   disable nasup service"
		Encapsulate "  -e   --enable    enable nasup service"
		Encapsulate "  -h   --help      this help message"
		Encapsulate "  -i   --info      dispays info about nastype"
		Encapsulate "  -r   --restart   restarts network services on local network."
		Encapsulate "  -s   --scan      scans for NAS drive on network."
		Encapsulate "  -S   --share     share folder / drive on LAN."
		Encapsulate "  -v   --version   dump version info and exit."
		Encapsulate ""
		Encapsulate "Example: ${PROGNAME} --help scan"
		FullBar;;
		ALL|d|disable)
		Encapsulate "Usage Disable;"
		Encapsulate "nasup -d"
		Encapsulate "Disables ${PROGNAME} service, stops the service and reports the status."
		FullBar;;
		ALL|e|enable)
		Encapsulate "Usage Enable;"
		Encapsulate "nasup -e"
		Encapsulate "Enables ${PROGNAME} service, start the service and reports the status."
		FullBar;;
		ALL|i|info)
		Encapsulate "Usage info;"
		Encapsulate "nasup -i <IPADDRESS>"
		Encapsulate "${PROGNAME} Will probe <IPADDRESS> on your LAN trying to discover the type of NAS drive"
		FullBar;;
		ALL|s|scan)
		Encapsulate "Usage Scan;"
		Encapsulate "nasup -s [nfs] [add / remove]"
		Encapsulate "Scans LAN for NAS drive(s) on your current network. The mount-point will be"
		Encapsulate "created at /media/NAS/, NAS1 etc. if multiple NAS's are detected. Not"
		Encapsulate "using -nfs will be mounted as cifs."
		Encapsulate " "
		Encapsulate "If the optional [add / remove] switch is omitted ${PROGNAME}"
		Encapsulate "will just report findings.	Add after completion and successfully"
		Encapsulate "finding the NAS'(s) will add the drive to the fstab for mounting as"
		Encapsulate "/media/NFS/, /media/NFS1/ etc. on boot-up. to your /etc/fstab"
		Encapsulate " "
		Encapsulate "Remove option will scan for NAS(s) and remove it / them from your fstab."
		FullBar;;
		ALL|r|restart)
		Encapsulate "Usage Restart;"
		Encapsulate "nasup -r [NFS/SMB]"
		Encapsulate "Restarts all network related services optionally selectively [nfs/smb]"
		Encapsulate "on your current local network."
		Encapsulate ""
		Encapsulate "Example: ${PROGNAME} --restart nfs"
		FullBar;;
		ALL|S|share)
		Encapsulate "Usage Share;"
		Encapsulate "nasup -S <nfs/smb> <add/remove/list> <MOUNTPOINT>"
		Encapsulate "Sets a drive or folder to be shared in <nfs/smb> on your current local network."
		Encapsulate "<MOUNTPOINT> must exist unless you are [list]ing current shares."
		Encapsulate "add will add/media/NFS/, /media/NFS1/ etc. on boot-up. to your /etc/fstab"
		Encapsulate " "
		Encapsulate "Remove option will remove it from your /etc/exports & restart the service."
		Encapsulate ""
		Encapsulate "Example: ${PROGNAME} --share nfs add /media/12TB/"
		FullBar;;
		ALL|v|version)
		Encapsulate "Usage version;"
		Encapsulate "nasup -v"
		Encapsulate "Displays nasup's version number and exits."
		FullBar;;
		ALL|h|help|\?)
		Encapsulate "Useage Help [COMMAND];"
		Encapsulate "nasup -h [COMMAND]"
		Encapsulate "Displays this message. For futher information nasup --help [COMMAND]"
		Encapsulate "or refer to the manpages."
		Encapsulate " "
		Encapsulate "man nasup"
		FullBar;;
	esac
	exit 0;
}

NFSSHARE () {
	if [[ "${DEBUG}" ]]; then
		echo "IN FUNCTION NFSSHARE DEBUGGING ADD:${ADD} LIST: ${LIST} REMOVE:${REMOVE} CONTAINS: ${CONTAINS} INSTALLED: ${INSTALLED}"
	fi
	if [[ "${LIST}" ]]; then
		ANY=$(showmount -e 127.0.0.1 | sed -n '1!p')
		if [[ "$ANY" ]]; then
			Columnize -t "SHARE" "ACCEPTED IP"
			Columnize "$ANY"
			FullBar
			exit 0;
			else
			Error "No shares detected."
			FullBar
			exit 0;
			fi
	fi
	if [[ "${ADD}" ]]; then
		EXISTS=0
		for EACH in "$@"
		do
			if [[ -d "${EACH}" ]]; then
				EXISTS=1
				SHAREFOLDER="${EACH}"
			else
				if [[ "${DEBUG}" ]]; then
					echo "IN FUNCTION NFSSHARE CONDITION ADD DEBUGGING EACH:${EACH}"
				fi
			fi
		done
		if [[ "${EXISTS}" ]]; then
			if [[ "${DEBUG}" ]]; then
				echo "debugging $@ in NFSSHARE FOLDER: ${SHAREFOLDER}"
			fi
			INEXPORTS=$( grep "${SHAREFOLDER}" "/etc/exports" )
			if [[ "$INEXPORTS" ]]; then
				Error "${SHAREFOLDER} already shared in /etc/exports"
				FullBar
				RestartServices
				exit 0;
			else
				Encapsulate "Setting /etc/exports entry for ${SHAREFOLDER}"
				if [[ "${UID}" == "0" ]]; then
					TESTING=$(echo "${SHAREFOLDER}	*(rw,sync,no_subtree_check)" | tee -a /etc/exports 2>/dev/null)
				else
					TESTING=$(echo "${SHAREFOLDER}	*(rw,sync,no_subtree_check)" | sudo tee -a /etc/exports 2>/dev/null)
				fi
				RestartServices "$@"
				ANY=$(showmount -e 127.0.0.1 | sed -n '1!p' | grep -v "${SHAREFOLDER}")
				if [[ "${ANY}" ]]; then
					Encapsulate "NFS Share: Success."
					FullBar
					exit 0;
				else
					Error "An Error occured adding NFS Share: ${SHAREFOLDER}."
					FullBar
					exit 0;
				fi
			fi
		else
			Error "Share folder does not exist."
		fi
	fi
		if [[ "${REMOVE}" ]]; then
			EXISTS=0
			for EACH in "$@"
			do
				if [[ -d "${EACH}" ]]; then
					EXISTS=1
					SHAREFOLDER="${EACH}"
				else
					if [[ "${DEBUG}" ]]; then
						echo "IN FUNCTION NFSSHARE CONDITION ADD DEBUGGING EACH:${EACH}"
					fi
				fi
			done
			INEXPORTS=$(grep "${SHAREFOLDER}" /etc/exports)
			if [[ "$INEXPORTS" ]]; then
				Encapsulate "Removing NFS Share: ${SHAREFOLDER} from /etc/exports"
				sed -i "\|${SHAREFOLDER}|d" /etc/exports
				#sed -ie "/${SHAREFOLDER}/d" /etc/exports
				Encapsulate "Success."
				FullBar
				exit 0;
			else
				Error "Not in /etc/exports: ${SHAREFOLDER}"
				FullBar
				exit 0;
			fi
		fi
}

SAMBASHARE () {
	if [[ "${DEBUG}" ]]; then
		echo "IN FUNCTION SAMBASHARE DEBUGGING ADD:${ADD} LIST: ${LIST} REMOVE:${REMOVE} CONTAINS: ${CONTAINS} INSTALLED: ${INSTALLED}"
	fi
	if [[ "${LIST}" ]]; then
		testparm -s
		FullBar
		exit 0;
	fi
	if [[ "${ADD}" ]]; then
		EXISTS=0
		for EACH in "$@"
		do
			if [[ -d "${EACH}" ]]; then
				EXISTS=1
				SHAREFOLDER="${EACH}"
			else
				if [[ "${DEBUG}" ]]; then
					echo "IN FUNCTION NFSSHARE CONDITION ADD DEBUGGING EACH:${EACH}"
				fi
			fi
		done
		if [[ "${EXISTS}" ]]; then
			if [[ "${DEBUG}" ]]; then
				echo "debugging $@ in NFSSHARE FOLDER: ${SHAREFOLDER}"
			fi
			#INEXPORTS=$( grep "${SHAREFOLDER}" "/etc/exports" )
			INEXPORTS=$( grep "${SHAREFOLDER}" "/etc/samba/smb.conf" )
			if [[ "${INEXPORTS}" ]]; then
				Error "${SHAREFOLDER} already shared."
				FullBar
				exit 0;
			else
				Encapsulate "Setting /etc/samba/smb.conf entry for ${SHAREFOLDER}"
				#TESTING=$(echo "${SHAREFOLDER}	*(rw,sync,no_subtree_check)" | tee -a /etc/exports 2>/dev/null)
				#Encapsulate "Setting global share"
				#EXAMPLE:
				#[12TB]
				#comment = 12 TB Raid 0 Array
				#path = /media/12TB
				#browseable = yes
				#read only = no
				#guest ok = no
				SHORT=$(basename "${SHAREFOLDER}")
				echo "UID=${UID}"
				if [[ "${UID}" == "0" ]]; then
					TESTING=$(echo "[${SHORT}]" | tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "comment = Entry added via Nasup" | tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "path = ${SHAREFOLDER}" | tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "browseable = yes" | tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "read only = no" | tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "guest ok = yes" | tee -a /etc/samba/smb.conf 2>/dev/null)
				else
					TESTING=$(echo "[${SHORT}]" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "comment = Entry added via Nasup" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "path = ${SHAREFOLDER}" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "browseable = yes" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "read only = no" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
					TESTING=$(echo "guest ok = yes" | sudo tee -a /etc/samba/smb.conf 2>/dev/null)
				fi
				ANY=$(grep -i "${SHAREFOLDER}" "/etc/samba/smb.conf" )
				if [[ "${ANY}" ]]; then
					Encapsulate "Samba Share: Success."
					RestartServices "$@"
					FullBar
					exit 0;
				else
					Error "An Error occured adding Samba Share: ${SHAREFOLDER}."
					FullBar
					exit 0;
				fi
			fi
		else
			Error "Share folder does not exist."
		fi
	fi
		if [[ "${REMOVE}" ]]; then
			EXISTS=0
			for EACH in "$@"
			do
				if [[ -d "${EACH}" ]]; then
					EXISTS=1
					SHAREFOLDER="${EACH}"
				else
					if [[ "${DEBUG}" ]]; then
						echo "IN FUNCTION NFSSHARE CONDITION ADD DEBUGGING EACH:${EACH}"
					fi
				fi
			done
			INEXPORTS=$(grep "${SHAREFOLDER}" /etc/exports)
			if [[ "$INEXPORTS" ]]; then
				Encapsulate "Removing NFS Share: ${SHAREFOLDER} from /etc/exports"
				sed -i "\|${SHAREFOLDER}|d" /etc/exports
				Encapsulate "Success."
				FullBar
				exit 0;
			else
				Error "Not in /etc/exports: ${SHAREFOLDER}"
				FullBar
				exit 0;
			fi
		fi
}

Share () {
	VersionDump
	CheckRoot "$@"
	ADD=$(echo "$@" | grep -i "add")
	REMOVE=$(echo "$@" | grep -i "remove")
	LIST=$(echo "$@" | grep -i "list")
	CONTAINS=$(echo "$@" | grep -i "nfs")
	if ! [[ "${ISARCH}" ]]; then
		INSTALLED=$(dpkg -l | grep "nfs-kernel-server")
	else
		PACMAN=$(type -p pacman)
		if [[ "${PACMAN}" ]]; then
			INSTALLED=$(pacman -Qs nfs-utils)
		fi
	fi
	SMB=$(echo "$@" | grep -i "smb\|samba")
	if [[ "${DEBUG}" ]]; then
		echo "IN FUNCTION SHARE DEBUGGING ADD:${ADD} LIST: ${LIST} REMOVE:${REMOVE} CONTAINS: ${CONTAINS} INSTALLED: ${INSTALLED}"
	fi
	if [[ "${CONTAINS}" && "${INSTALLED}" ]]; then
		if ! [[ -f "/etc/exports" ]]; then
			if ! [[ "${ISARCH}" ]]; then
				Error "NFS server is not installed: apt-get install nfs-kernel-server"
				FullBar
				exit 0;
			else
				Error "NFS server is not installed: pacman -Syuu nfs-utils"
				FullBar
				exit 0;
			fi
		fi
		if [[ "${ADD}" ]] || [[ "${REMOVE}" ]] || [[ "${LIST}" ]]; then
			if [[ "${CONTAINS}" ]]; then
				NFSSHARE "$@"
			fi
		else
			Error "Invaild command switch: $@"
			Help "share"
			exit 0;
		fi
	fi
	if [[ "${SMB}" ]]; then
		INSTALLED=$(dpkg -l | grep "samba-clent")
		if [[ "${INSTALLED}" ]]; then
			INSTALLED="Yes"
		fi
		if [[ "${INSTALLED}" == "Yes" ]]; then
			Error "Samba Client is not installed: apt-get install samba-client"
		fi
		if [[ "${DEBUG}" ]]; then
			echo "IN FUNCTION SHARE DEBUGGING ADD:${ADD} LIST: ${LIST} REMOVE:${REMOVE} CONTAINS: ${CONTAINS} INSTALLED: ${INSTALLED}"
		fi
		if [[ "${ADD}" ]]; then
			if [[ "${SMB}" ]]; then
				SAMBASHARE "$@"
			fi
		fi
		if [[ "${REMOVE}" ]]; then
			if [[ "${SMB}" ]]; then
				SAMBASHARE "$@"
			fi
		fi
		if [[ "${LIST}" ]]; then
			if [[ "${SMB}" ]]; then
				SAMBASHARE "$@"
			fi
		fi
	fi
	RestartServices "$@"
	Error "Something occured beyond my control."
}

TestSpeed () {
	VersionDump
	Timer "Start" "Internet Speed Test."
	Encapsulate "Testing detection speed of all Samba shares on your network."
	smbtree -b -N | sed -n '1!p' | grep -iEv 'IPC|PRINT'
	FullBar
	Timer "Stop" "Internet Speed Test."
}
	#echo "USER:		${USER}"
	#echo "SUDO_USER: ${SUDO_USER}"
	#echo "Systemd: USER:$@"
	if [[ -d "/home/" ]]; then
		cd "/home/" || exit 1;
		THEUSER=(*);
		if [[ "${#THEUSER[@]}" == "1" ]]; then
			IUSER="${THEUSER}"
		fi
		cd "${CURRENT}" || exit 1;
	fi
Timer "Start" "${APPNAME}"
	#echo "Testing: ${IUSER}"
	#users
	#who
	#for EACH in /media/NAS*; do chown -R ${USER}:${USER} "${EACH}"; done
	#mount -a
# Not used until I implement AFP
# GrabOptions "$@"
# Command switch interpreter
EnableService () {
	ISINSTALLED=$(type -p systemctl)
	if [[ ${ISINSTALLED} ]]; then
		Encapsulate "Enabling Nasup Service."
		systemctl enable nasup.service
		Encapsulate "Starting Nasup Service."
		systemctl start nasup.service
		systemctl status nasup.service
	fi
}
DisableService () {
	ISINSTALLED=$(type -p systemctl)
	if [[ ${ISINSTALLED} ]]; then
		Encapsulate "Disabling Nasup Service."
		systemctl disable nasup.service
		Encapsulate "Stoping Nasup Service."
		systemctl stop nasup.service
		systemctl status nasup.service
	fi
}
case "${1}" in
	-e|--enable) EnableService "$@"; exit 0;;
	-d|--disable) DisableService "$@"; exit 0;;
	-h|--help|-\?) Help "$@"; exit 0;;
	-i|--info) NASType "$@"; exit 0;;
	-v|--version) VersionDump "$@"; exit 0;;
	-s|--scan) Scan "$@"; exit 0;;
	-S|--share) Share "$@"; exit 0;;
	-r|--restart) RestartServices "$@"; exit 0;;
	-t|--testspeed) TestSpeed "$@"; exit 0;;
	#Undocumented / un-implemented switch
	-m|--mount-nas) MountNAS "$@"; exit 0;;
	*) Help; exit 0;;
esac
# ==============================================================================
# This code was automatically cleaned up using code-cleanup
# title			:code-cleanup
# description	:Bash code cleanup script
# Author		:theemahn
# date			:10/23/2013
# version		:1.7.2-1
# http://ultimateedition.info/
# ==============================================================================
