#!/bin/bash
do {
	#////////////////////////////////////
	# 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
	#////////////////////////////////////

	setvar INPUT = '0'
	if [[ $1 =~ ^-?[0-9]+$ ]] {
		setvar INPUT = "$1"
	}

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

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

	proc 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 )) {

		setvar 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)
		setvar CHOICE = ""$?
		if (( $CHOICE == 0 )) {

			setvar 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

		}

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

		Apply_And_Mount

	}

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