#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Function:
	# - Setup and apply DietPi NFS details
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Menu system that allows users to change NFS details stored in dietpi.txt and automatically mount.
	# - Applies details to /etc/fstab
	# - Mounts to /mnt/nfs_client if successful
	#
	# Usage:
	# - /DietPi/dietpi/func/dietpi-set_nfsclient	= Menu
	# - /DietPi/dietpi/func/dietpi-set_nfsclient 1	= Apply and mount using settings in dietpi.txt
	#////////////////////////////////////

	INPUT=0
	if [[ $1 =~ ^-?[0-9]+$ ]]; then
		INPUT=$1
	fi

	#Import DietPi-Globals ---------------------------------------------------------------
	. /DietPi/dietpi/func/dietpi-globals
	G_CHECK_ROOT_USER
	export G_PROGRAM_NAME='DietPi-Set_nfsclient'
	#Import DietPi-Globals ---------------------------------------------------------------

	#/////////////////////////////////////////////////////////////////////////////////////
	#curlftpfs data
	#/////////////////////////////////////////////////////////////////////////////////////
	OPTION=0
	CHOICE=0
	nfsclient_ipaddress=$(grep -m1 '^CONFIG_NFSCLIENT_ADDRESS=' /DietPi/dietpi.txt | sed 's/.*=//')

	Apply_And_Mount(){

		#Apply to fstab
		sed -i "/\/mnt\/nfs_client/c $nfsclient_ipaddress:\/ \/mnt\/nfs_client nfs4 auto,_netdev 0  0" /etc/fstab

		#Mount up
		mount -a

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	#-----------------------------------------------------------------------------------
	#Menu
	if (( $INPUT == 0 )); then

		OPTION=$(whiptail --inputbox "Please enter the NFS server IP address\n - eg: 192.168.0.123" 9 65 "$nfsclient_ipaddress" --title "NFS Client Setup" 3>&1 1>&2 2>&3)
		CHOICE=$?
		if (( $CHOICE == 0 )); then

			nfsclient_ipaddress=$OPTION

			#Unmount if connected
			clear
			echo -e "\n\n Attempting mount, please wait...."
			umount /mnt/nfs_client &> /dev/null

			#Save to Dietpi.txt
			sed -i "/CONFIG_NFSCLIENT_ADDRESS=/c\CONFIG_NFSCLIENT_ADDRESS=$nfsclient_ipaddress" /DietPi/dietpi.txt

			Apply_And_Mount

		fi

	#-----------------------------------------------------------------------------------
	#Apply and mount. Using settings from dietpi.txt
	elif (( $INPUT == 1 )); then

		Apply_And_Mount

	fi

	#-----------------------------------------------------------------------------------
	exit
	#-----------------------------------------------------------------------------------
}