#!/bin/bash

export CMD=`basename $0`
export VERBOSE="true"

. /etc/vhspare/vhspare.conf
. /etc/vhspare/vhspare-functions.sh
. /lib/ku-base/log.sh

usage()
{
	echo "usage: $CMD [-q] [-n] [-f] { -a | virtsystem(s) }" >&2
	exit 1
}

sync_on_main_server()
{
	local req_sys="$*"
	local virtsys=
	local loc_fs=
	local rem_fs=
	local otherparms=
	local inputfile="/etc/vhspare/sync-main.conf"

	[ -f $inputfile ] || return 0

	ku_log " syncing from $inputfile"

	exec 9<&0 <$inputfile

	while read virtsys loc_fs rem_fs otherparms
	do
		case $virtsys in
		  \#*) ;;
		  "") ;;
		  *)	do_it=false
			if $all_systems
			then
				do_it=true
			else
				is_in_list "$virtsys" $req_sys && do_it=true
			fi
			$do_it && vhspare_sync_fs $virtsys $loc_fs $rem_fs $otherparms
			;;
		esac
	done

	exec 0<&9 9<&-
}




sync_on_spare_server()
{
	local req_sys="$*"
	local virtsys=
	local loc_fs=
	local rem_fs=
	local otherparms=
	local inputfile="/etc/vhspare/sync-spare.conf"

	[ -f $inputfile ] || return 0

	ku_log " syncing from $inputfile"

	exec 9<&0 <$inputfile

	while read virtsys rem_fs loc_fs otherparms
	do
		case $virtsys in
		  \#*) ;;
		  "") ;;
		  *)	do_it=false
			if $all_systems
			then
				do_it=true
			else
				is_in_list "$virtsys" $req_sys && do_it=true
			fi
			$do_it && vhspare_sync_fs $virtsys $rem_fs $loc_fs $otherparms
			;;
		esac
	done

	exec 0<&9 9<&-
}


is_in_list()
{
	local string=$1	; shift
	local str=
	for str in $*
	do
		[ X"$string" == X"$str" ] && return 0
	done
	return 1
}



# (MAIN)

all_systems=false
confirm="confirm"

ku_cap_logfile


while [ $# != 0 ]
do
    case $1 in
	-n)
		echo "(running in dummy mode)" >&2
		export DOIT="echo "
		;;
	-q)	VERBOSE=false ;;
	-a)	all_systems=true ;;
	-f)	confirm=true ;;
	--)	break ;;
	-*)	usage ;;
	*)	break ;;
    esac
    shift
done


[ $# == 0 ] && {
	$all_systems || usage
}

ku_log "SPARE SYNC REQUESTED: $@"

vhspare_run_parts /etc/vhspare/pre-common

echo "
	AGGIORNAMENTO SERVER MAIN -> SPARE

	DA (main):	$MAIN_SERVER
	A (spare):	$SPARE_SERVER
	PARMS:	      	$@

	SEI SUL SERVER: $MYROLE

	Nota: l'operazione puo' durare molto a lungo.
"

$confirm "Procedo? (s/n)" || exit 0

if [ $MYROLE == "main" ]
then
	sync_on_main_server $@
else
	sync_on_spare_server $@
fi

vhspare_run_parts /etc/vhspare/sync

ku_log "SYNC ENDED"
exit 0
