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

getConfigGeneral() {
	case $key in
		'max-load')
			# Target system 1-minute load average
			# concurrency is adjusted to stay near this
			expr='^[0-9]*$'
			if [[ $value =~ $expr ]]
			then
				maxload="$value"
			else
				echo "Invalid max-load value: $value" >&2
				exit $ELOAD
			fi
			unset expr
		;;
		'load-interval')
			# How often (seconds) to adjust worker count
			expr='^[0-9]*$'
			if [[ $value =~ $expr ]]
			then
				loadinterval="$value"
			else
				echo "Invalid load-interval value: $value" >&2
				exit $EINTERVAL
			fi
			unset expr
		;;
		'ionice')
			if which ionice >/dev/null
			then
				read class niceness <<<"$value"
				case $class in
					1)
						# real-time class, only root can do that
						if (( UID ))
						then
							echo "IO class 'realtime' is"\
							"not available to unprivileged"\
							"users" >&2
							exit $EIONICE
						fi
						if [ -n "$niceness" ]		\
						&& (( niceness >= 0 && niceness <= 7 ))
						then
							ionice="ionice -c1 -n$niceness "
						else
							echo "Invalid IO priority"\
							"'$niceness'" >&2
							exit $EIONICE
						fi
					;;
					2)
						# Best-effort class; niceness 0 (highest) to 7 (lowest)
						if [ -n "$niceness" ]		\
						&& (( niceness >= 0 && niceness <= 7 ))
						then
							ionice="ionice -c2 -n$niceness "
						else
							echo "Invalid IO priority"\
							"'$niceness'" >&2
							exit $EIONICE
						fi
					;;
					3)
						# Idle class: only gets I/O when no other process needs it
						ionice="ionice -c3 "
					;;
					*)
						echo "Invalid ionice class $value"\
						>&2
						exit $EIONICE
					;;
				esac
			fi
		;;
		'temporary-directory')
			# Directory for
			# * SQLite FIFOs
			# * intermediate WAV files
			# * debug logs
			tempdir="$value"
		;;
		'database')
			# Path to the SQLite database file
			database="$value"
		;;
		'skip-timestamp-microsec')
			# If non-zero, ignore sub-second precision in file timestamps
			# Useful on filesystems that don't preserve microseconds
			skip_us_timestamp="$value"
		;;
		debug)
			# Allow config file to raise debug level (but not lower it)
			(( value > debug )) && debug=$value
		;;
	esac
}
