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

setup() {
	cat <<-EOStartConf
You will now be asked (hopefully) simple questions to help you configure AtOM's
behavior.

Completion is available for prompts asking for a paths or filenames.
	EOStartConf
	# Collect all configuration sections in order
	setupGeneral
	setupSource
	setupDestinations
	# Clear the regex used by validation loops inside setup sub-functions
	unset expr
	# Write the newly gathered config to a temp file so the original is
	# preserved until the user confirms
	writeConfig >"$cffile".tmp
	# Unset all config variables so getConfig can repopulate them cleanly
	# from the temp file; avoids stale values leaking into the review
	unset				\
		sourcepath		\
		skippeddirectories	\
		maxload			\
		loadinterval		\
		ionice			\
		tempdir			\
		database		\
		debug			\
		destinationchannels	\
		destinationfat32compat	\
		destinationcopymime	\
		destinationcopyext	\
		destinationformat	\
		destinationfrequency	\
		destinationid		\
		destinationloss		\
		destinationmaxbps	\
		destinationnormalize	\
		destinationpath		\
		destinationquality	\
		destinationrename	\
		destinationnoresample	\
		destinationrenamepath	\
		destinationskipmime
	# Re-declare per-destination variables as associative arrays so
	# getConfig can populate them with [destinationname]=value entries
	declare -A			\
		destinationchannels	\
		destinationfat32compat	\
		destinationcopymime	\
		destinationcopyext	\
		destinationformat	\
		destinationfrequency	\
		destinationid		\
		destinationloss		\
		destinationmaxbps	\
		destinationnormalize	\
		destinationpath		\
		destinationquality	\
		destinationrename	\
		destinationnoresample	\
		destinationrenamepath	\
		destinationskipmime
	# Point getConfig at the temp file so the review reflects exactly what
	# would be written, not the old on-disk config
	oldcffile="$cffile"
	cffile="$cffile".tmp
	getConfig
	{
		echo $'Please review your new configuration:\n'
		printConfig
	}| less -F -e
	# Restore the original config path before deciding whether to commit
	cffile="$oldcffile"
	read -p'Write config file? [y/N] ' do_write
	case $do_write in
		y)
			mv -f "$cffile".tmp "$cffile"
		;;
		*)
			rm "$cffile".tmp
			read -p'Re-run (s)etup, (q)uit [s/Q] ' do_rerun
			case $do_rerun in
				s)	setup	;;
				*)	exit	;;
			esac
		;;
	esac
	read -p'Run index and conversion now? [Y/n] ' do_run
	case $do_run in
		n)	exit	;;
		*)		;;
	esac
}
