#!/bin/bash
#
# __copy1__
# __copy2__
#
# keep in sync user work directories with various repositories
# using the kusa config database definitions (look also in
# $HOME/.kuconf subdir)
#
CMD=`basename $0`
verbose=true
interactive=true
do_download=true
tags=

# (FUNCTIONS)

usage()
{
	echo "
usage: $CMD [options] [tags]

options:
 -d|--debug	activate debug
 -v|--verbose	be verbose (default)
 -q|--quiet	be quiet
 -b|--batch	non interactive
 -u|--upload	upload (default is donwload)
 --download	download
" >&2
	exit 1
}

required_ku_conf()
{
	local stat=0
	jtconf $1 || {
		stat=$?
		message "required $1 missing, skip entry"
		return $stat
	}
	return 0
}

bool_ku_conf()
{
	local result=`jtconf $* 2>/dev/null`
	result=`echo "$result" | tr '[A-Z]' '[a-z]'`
	case "$result" in
		""|0|n|no|false)	echo "false" ;;
		1|y|yes|true)		echo "true" ;;
	esac
}

message()
{
	echo -e "$@" >&2
	return 0
}

pdebug()
{
	$debug || return 0
	message "D>>" "$@"
	return 0
}



# (MAIN)

# parms
#
while [ $# != 0 ]
do
	case $1 in
		--download)	do_download=true ;;
		-u|--upload)	do_download=false ;;
		-b|--batch)	interactive=false ;;
		-q|--quiet)	verbose=false ;;
		-v|--verbose)	verbose=true ;;
		-d|--debug)	debug=true ;;
		
		# states
		#
		--on-session-login)	require_in_session_login=true ;;
		--on-session-logout)	require_in_session_logout=true ;;
		--on-timer)		require_in_timer=true ;;

		-*|"")		usage ;;
		*)		tags="$tags $1" ;;
	esac
	shift
done


# looks at slots definitions and try to sync (download/upload)
#
for entry in `jtconf --list sync.`
do
	# this is required to distinguish valid entries from defaults/inactive
	#
	active=`jtconf $entry.active 2>/dev/null` || continue

	# required parms
	#
	protocol=`	required_ku_conf $entry.protocol` || continue
	server=`	required_ku_conf $entry.server` || continue
	slots=`		required_ku_conf $entry.slots` || continue
	local=`		required_ku_conf $entry.local` || continue
	remote=`	required_ku_conf $entry.remote` || continue

	# optional parms
	#
	on_session_login=`	bool_ku_conf $entry.on_session_login 2>/dev/null`
	on_session_logout=`	bool_ku_conf $entry.on_session_logout 2>/dev/null`
	on_timer=`		bool_ku_conf $entry.on_timer 2>/dev/null`
	desc=`			jtconf $entry.desc 2>/dev/null`

	desc=${desc:-"`echo $entry | sed -e 's/^sync\.//'`"}

	# is pertinent?
	#
	$require_in_session_login && {
		$on_session_login || {
			pdebug "$entry: on_session_login required, skip"
			continue
		}
	}
	$require_in_session_logout && {
		$on_session_logout || {
			pdebug "$entry: on_session_logout required, skip"
			continue
		}
	}
	$require_in_timer && {
		$on_timer || {
			pdebug "$entry: on_timer required, skip"
			continue
		}
	}

	echo "try to update $desc ($entry)"
done

exit 0
