#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# 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.

# 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.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

setupDestinations() {
	cat <<-EODesc


[Destinations]
    Finally, we'll setup your destination(s).
	EODesc
	if (( ${#destinations[@]} ))
	then
		cat <<-EODesc

    [Existing destinations]
        We will review your currently configured destinations. Clear the 'Name'
        field to remove one.
		EODesc
		for destination in "${destinations[@]}"
		do
			cat <<-EODesc

    Name (string):
        A simple name for this destination. Clear to remove this destination.
			EODesc
			expr='^[A-z0-9]*$'
			comeagain() {
				read -p'Name: ' -e -i"$destination" value
				if [ -z "$value" ]
				then
					read				\
					-p"Really remove destination $destination? [y/N]"
					if [[ $REPLY == y ]]
					then
						removeDestination "$destination"
						continue
					else
						value="$destination"
					fi
				elif ! [[ $value =~ $expr ]]
				then
					echo "Invalid name $value."	\
						'Please use only'	\
						'alphanumeric characters.' >&2
					comeagain
				fi
			}
			comeagain
			destination="$value"
			setupDestination
		done
	fi
	cat <<-EODesc

    [New destinations]
        This section will loop until you enter an empty 'Name'.
	EODesc
	for (( i=0 ; 1 ; i++ ))
	do
		cat <<-EODesc

    Name (string):
        A simple name for this destination. Empty string to end this
        configuration loop.
		EODesc
		expr='^[A-z0-9]*$'
		comeagain() {
			read -p'Name: ' value
			[ -z "$value" ] && return 1
			if ! [[ $value =~ $expr ]]
			then
				echo "Invalid name $value. Please use"	\
					'only alphanumeric characters.' >&2
				comeagain
			fi
		}
		comeagain || break
		destination="$value"
		setupDestination
	done
}
