#!/bin/bash
#
# __copy1__
# __copy2__
#
CMD=$(basename $0)
CMDVER="3.4"
CMDSTR="$CMD v$CMDVER (2026-01-19)"

set -e -u

usage()
{
	print_usage >&2
	[ $# != 0 ] && echo -e "\n$*\n" >&2
	exit 127
}


print_usage()
{
	echo "
== $CMDSTR = kubackup, print config option for system ==

usage:	$CMD [options] global_key
	$CMD [options] sysname key
	$CMD [options] --export sysname

options:
  -c|--config FILE	uses 'FILE' instead of $CfgFile
  			(or /etc/kubackup-run-FILE.conf)
  -e|--export		dumps all system vars in a format suitable to
  			be evalued from shell; each variable is prefixed
			by 'SYS_' and exported
  -b|--bool|--tf)	does not print true/false value, but exits with
  			0=true or 1=false, valid only for boolean vars
			(use --help for details)
  -t|--terse		clean output (removes comments and empty lines)
  -D|--debug		debug messages
  -h|--help		prints help and exits
"
	return 0
}


print_help()
{
	print_usage

	echo "
- sysname must match the file <sysname>.conf in \$CONFDIR 
- the 'terse' option is meaningfull only for certain keys, ie: modules
- terse and bool options are ignored if --export mode is used


SYSTEM DEFINES
$system_keys $system_pseudo_keys

- keys marked by 'T/F' does prints nothing, return 0 or 1 for true/false
- keys marked by (F) are a file content (like 'modules')


GLOBAL DEFINES
$global_keys

EXIT VALUES
  0	all ok
  0/1	true / false	(for allowed keys)
  2	invalid global key
  3	unknown system name
  4	invalid system key
  5	missing required key
  6	old config files format detected, conversion needed
  10	cannot retrieve value (usually for lack of permissions)
  11	invalid value (where checked)
  12	missing file
  127	usage error

ENVINRONMENT

  CONFDIR	used if set, overrides definition in config file
"
	return 0
}


terse_modulesfile()
{
	local module=
	local dir=
	local user=
	local pass=
	local args=
	local default_user=$(get_system_define $sys user)
	local default_pass=$(get_system_define $sys password)

	if $f_terse
	then
		sed -e 's/[[:space:]]*#.*//' -e '/^[[:space:]]*$/d' | while :
		do
			read module dir args || break
			user=
			pass=
			case $module in
			  *:*@*)
				# user and pass embededd in module name
				args="$user $pass $args"
				user=$(echo "$module" | cut -d'@' -f1)
				pass=$(echo "$user" | cut -d':' -f2)
				user=$(echo "$user" | cut -d':' -f1)
				module=$(echo "$module" | cut -d'@' -f2)
				;;
			  *)
				user=$default_user
				pass=$default_pass
				;;
			esac
			echo "$module $dir $user $pass $args"
		done
	else
		cat
	fi
	return 0
}

get_global_define()
{
	case $1 in
	  workdir)
		[ -f /etc/default/kusa-paths ] && . /etc/default/kusa-paths
		KUSA_PATH_WORKDIR=${KUSA_PATH_WORKDIR:-"/var/tmp"}
		echo "$KUSA_PATH_WORKDIR/kubackup"
		;;
	  port)
		[ -f /etc/default/kusa-netservices ] && . /etc/default/kusa-netservices
		echo ${KUSA_NETSERVICE_HDBACKUP:-"19001"}
		;;
	  statusport)
		[ -f /etc/default/kusa-netservices ] && . /etc/default/kusa-netservices
		echo ${KUSA_NETSERVICE_HDBACKUP_STATUS:-"19003"}
		;;
	  ex*)
	  	[ -f "$CONFDIR/_common_excludes" ] && cat "$CONFDIR/_common_excludes"
		;;
	  winex*)
	  	[ -f "$CONFDIR/_win_common_excludes" ] && cat "$CONFDIR/_win_common_excludes"
		;;
	  prec*)
	  	[ -f "$CONFDIR/_groups_precedences" ] && cat "$CONFDIR/_groups_precedences"
		;;

	  # env vars from config
	  label)	echo $LABEL ;;
	  bckdisk)	echo $BCKDISK ;;
	  bckdir)	echo $BCKDIR ;;
	  email)	echo $EMAIL ;;
	  mail)		echo ${MAIL:-} ;;
	  lang)		echo ${KUBACKUP_LANG:-C} ;;
	  timeout)	echo ${Timeout:-} ;;
      	  *)
		echo "error: global define, invalid key '$1'" >&2
		return 2
		;;
	esac
	return 0
}


get_system_define()
{
	local sys=
	local key=
	local need_bool=false
	local out=

	[ "X${1:-}" = "X--bool" ] && {
		need_bool=true
		shift
	}
	sys=$1
	key=$2

	local disabled='false'
	local direct='false'
	local uuid=
	local address=
	local allow=
	local groups=
	local precedence=
	local cache=
	local slot=
	local rotations=
	local timeout=
	local modulesfile=
	local port=
	local user=
	local password=

	[ -e "$CONFDIR/${sys}_uuid" ] && {
		echo >&2
		echo "error: old config file format detected, conversion needed" >&2
		echo "       run the following command in config dir:" >&2
		echo >&2
		echo "          bash /usr/share/doc/kubackup/convert-to-v3.sh" >&2
		echo >&2
		return 6
	}

	[ -s "$CONFDIR/$sys.conf" ] || {
		echo "system '$sys' unknown" >&2
		return 3
	}

	# read config file
	out=$(grep "^[A-Za-z][A-Za-z0-9]*=" "$CONFDIR/$sys.conf") || {
		return 10
	}
	eval "$out"

	# required
	[ "X$uuid" = "X" ] && {
		echo "$CMD: error, required key 'uuid' not defined" >&2
		return 5
	}

	# modulesfile, depends on file presence
	case $modulesfile in
	  /*)	# absolute path, used as-is
	  	;;
	  "")	# default (only existent files)
	  	modulesfile="$CONFDIR/${sys}_modules"
		[ -f "$modulesfile" ] || modulesfile=
		;;
	  *)	# relative path
	  	modulesfile="$CONFDIR/$modulesfile"
	esac
	[ "X$modulesfile" != "X" ] && {
		[ -f "$modulesfile" ] || {
			echo "$CMD: error, file '$modulesfile' not found" >&2
			return 12
		}
		direct='true'
	}

	# overrides, or inherithed from file presence
  	[ -f "$CONFDIR/${sys}_disabled" ]	&& disabled='true'

	$need_bool && {
		case $key in
		  # TRUE/FALSE definitions, does not echoes nothing, uses retval
		  disabled)	$disabled && return 0 || return 1 ;;
		  enabled)	$disabled && return 1 || return 0 ;;
		  direct)	$direct && return 0 || return 1 ;;
		  *)
		  	echo "error: system '$sys', invalid key '$key'" >&2
			return 4
			;;
		esac
	}

	# normalizazions
	slot=${slot:-$(echo $sys | sed -e 's/\..*//')}
	case $rotations in
	  "")	rotations=0 ;;
	  1)	rotations=0 ;; # rotations=1 means no rotations at all
	  [1-9]|[1-9][0-9]|[1-9][0-9][0-9]) ;; # ok
	  *)	echo "$CMD: error, invalid value rotations='$rotations', must be a positive integer" >&2
	  	return 11
		;;
	esac

    	case $key in
	  uuid)		echo $uuid ;;
	  address)	echo $address ;;
	  allow)	echo $allow ;;
	  groups)	echo $groups ;;
	  precedence)	echo $precedence ;;
	  slot)		echo $slot ;;
	  rotations)	echo $rotations ;;
	  timeout)	echo $timeout ;;
	  cache)	echo $cache ;;
	  modulesfile)	echo $modulesfile ;;
	  port)		echo $port ;;
	  user)		echo $user ;;
	  password)	echo $password ;;
	  disabled)	$disabled && echo 'true' || echo 'false' ;;
	  enabled)	$disabled && echo 'false' || echo 'true' ;;
	  direct)	$direct && echo 'true' || echo 'false' ;;
	  modules)
		[ "X$modulesfile" != "X" ] && {
			out=$(cat "$modulesfile") || {
				return 10
			}
			echo -e "# $sys - modules\n# file: $modulesfile\n#\n$out" | terse_modulesfile
		}
		;;
    	  *)
		echo "error: system '$sys', invalid key '$key'" >&2
		return 4
		;;
    	esac

	return 0
}




# (MAIN)

CfgFile="/etc/kubackup-run.conf"

# env overrides (saves for later use)
env_confdir=${CONFDIR:-}

CONFDIR="/etc/kubackup"

system_keys="
  uuid		the unique uuid for the system
  address	hostname or address
  port		use custom port for remote rsync daemon connection
  user		rsync module user
  password	rsync module password
  slot		backup subdirectory
  rotations	number of rotations, if active, 0 otherwise
  groups	groups list
  precedence	system precedence override
  timeout	rsync timeout override
  modulesfile	filename of modules, defaults to <sys>_modules
  allow		list of allowed ip address (only for remote backups)
  cache		cache dir, if used
"
system_pseudo_keys="
  enabled	T/F  is enabled
  disabled	T/F  is disabled
  direct	T/F  has modules defined (direct rsync call)
  modules	(F) only for direct backups, list of remote directories
"

global_keys="
  workdir	path of working directory
  port		network service port for remote backups	
  statusport	network service port for remote backup status
  excludes	content of _common_excludes file (if any)
  winexcludes	content of _win_common_excludes file (if any)
  precedence	content of _groups_precedences (if any)
"

requires_arg="option requires an argument"

# load main config file
[ -r $CfgFile ] || {
	echo "error: $CMD, cannot read '$CfgFile'" >&2
	exit 10
}
. $CfgFile

# env overrides?
[ "X$env_confdir" != "X" ] && CONFDIR="$env_confdir"

# then eval parms
#
VERBOSE=false
DEBUG=false
f_terse=false
need_bool=
mode=

while [ $# != 0 ]
do
  case "$1" in
    -c|--config)
    	[ $# -lt 2 ] && usage "config $requires_arg"
	shift
	CfgFile=$1
	[ -f $CfgFile ] || {
		CfgFile=/etc/kubackup-run-$1.conf
	}
	[ -f $CfgFile ] || {
		echo "error: can't find config file '$1' or /etc/kubackup-run-$1.conf" >&2
		exit 127
	}
	[ -r $CfgFile ] || {
		echo "error: $CMD, cannot read '$CfgFile'" >&2
		exit 10
	}
	. $CfgFile || exit 127
	;;

    -h|--help)		print_help; exit 0 ;;
    -t|--terse)		f_terse=true ;;
    -b|--bool|--tf)	need_bool='--bool' ;;
    -e|--export)	mode="export" ;;
    -D|--debug)		DEBUG=true  ;;
    -)			break ;;
    -*|"")		usage "usage error: unknown option '$1'" ;;
    *)			break ;;
  esac
  shift
done

# 2026-01-19
# temporary check for format change
#
ls $CONFDIR/*.conf >/dev/null 2>&1 && {
	egrep -q '^user=|^password=' $CONFDIR/*.conf || {
		echo >&2
		echo "** $CMD ERROR **" >&2
		echo >&2
		echo "SINCE VERSION ku26.01a THE FORMAT OF MODULES FILES FILE" >&2
		echo "CHANGED, PLEASE EDIT THEM:" >&2
		echo >&2
		echo "  - REMOVE user AND password COLUMNS FROM MODULES FILE" >&2
		echo "  - ADD user='....' AND password='.......' TO *.conf FILES" >&2
		echo "  - OR USE user:password@modulename EMBEDDED FORM" >&2
		echo >&2
		echo "SEE TEMPLATE FILE _modules_1fs AS EXAMPLE" >&2
		echo >&2
		echo "(WILL NOT PROCEED UNTIL THIS IS FIXED)" >&2
		echo >&2
		exit 1
	}
}

[ "$mode" = "export" ] && {
  	[ $# != 1 ] && usage "usage error: export mode requires only 'sysname' param"
	sys=$1
	get_system_define $sys uuid >/dev/null || exit $?

	# the system name itself
	echo "export SYS_name='$sys'"

	# the variables
  	for key in $(echo "$system_keys" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]].*//' -e '/^$/d')
	do
		val=$(get_system_define $sys $key) || exit $?
		echo "export SYS_$key='$val'"
	done
	exit 0
}

retval=0

case $# in
  1)	get_global_define "$1" || retval=$? ;;
  2)	get_system_define $need_bool "$1" "$2" || retval=$? ;;
  *)	usage "usage error: missing or too many parms" ;;
esac

exit $retval


# HISTORY
#
# 3.4 2026-01-10 lc
# - add: user and password system setting
# - mod: changed format of modules_file (removed user/pass fields, now
#	 you must use .conf settings, or embed into module name using
#	 the form user:pass@modulename
#
# 3.3 2024-09-20 lc
# - new: started this embedded history
# - add: 'port' keyword in systems sections
