#!/bin/bash
#
# ::copy::
# ::maintainer::
#
CMD=$(basename $0)

KU_LOCKFILE=/var/run/$CMD.lock
LOGSYSLOG=false

. /lib/ku-base/log.sh
. /lib/ku-base/lock.sh

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

options:
  --remote sys	set the remote system name to be sync-ed
  -v|--verbose	verbose, writes on stdout instead of logfile, too
  -q|--quiet	quiet, only logfile output
  -n|--dry-run	don't execute, only show actions
  -D|--debug	run in debug mode
  -x|--execute	execute

current (default) values:
 verbose: $VERBOSE
 execute: $F_EXEC
 REMOTE:  $REMOTE
 USERS:   $USERS

users can be expressed as 'user,remotesys', where remotesys will
overrides the one defined in \$REMOTE variable
" >&2
	[ $# != 0 ] && echo -e "\n$@\n"
	exit 1
}

cleanup()
{
	ku_lock_remove
	return 0
}

mylog()
{
	$VERBOSE || ku_log "$@"
	$VERBOSE && echo "$@"
	return 0
}




# (MAIN)

[ $(id -u) == 0 ] || {
	echo "you need to be 'root' to run this command" >&2
	exit 1
}

VERBOSE=false
DEBUG=false
F_EXEC=false
RunCmd="/usr/sbin/ku-mail-dovecot-sync"
RunCmdExecFlag=""
DebugFlag=
defaults_file="/etc/default/$CMD"
REMOTE=
USERS=
RUN=true

[ -f $defaults_file ] && . $defaults_file

[ "X$RUN" != "Xtrue" ] && exit 0

while [ $# != 0 ]
do
 case $1 in
  -n|--dry-run)	F_EXEC=false; RunCmdExecFlag="" ;;
  -x|--execute)	F_EXEC=true; RunCmdExecFlag="-x" ;;
  -q|--quiet)	VERBOSE=false ;;
  -v|--verbose)	VERBOSE=true ;;
  -D|--debug)	DEBUG=true ; DebugFlag="-D" ;;
  --remote)
  	shift
	[ $# = 0 ] && usage "option --remote requires an argument"
	REMOTE=$1
	;;
  --)		break ;;
  -*)		usage ;;
  *)		USERS="$USERS $1" ;;
 esac
 shift
done

[ "X$USERS" = "X" ] && {
	echo "error: you must pass a user list or define a space" >&2
	echo "	separated list in \$USER variable in the defaults" >&2
	echo "	file '$defaults_file'" >&2
	exit 1
}
[ "X$REMOTE" = "X" ] && {
	if echo "$USERS" | grep -q ','
	then
		echo "warning, no \$REMOTE defined, will use only explicit remotes" >&2
	else
		echo "error: you must pass a remote system (via --remote arg)" >&2
		echo "	or define the \$REMOTE variable in the defualts" >&2
		echo "	file '$defaults_file'" >&2
		exit 1
	fi
}

$F_EXEC


msg=$(ku_lock) || {
	mylog "$msg"
	exit 0
}

$VERBOSE || {
	ku_cap_logfile
	exec >>$LOGFILE 2>&1
}

trap "mylog '*INTR*'; cleanup; exit 255" 1 2 3
trap "cleanup" EXIT


mylog "== started F_EXEC=$F_EXEC"

status=0

for user in $USERS
do
	if echo $user | grep -q ','
	then
		remote=$(echo $user | cut -d',' -f2)
		user=$(echo $user | cut -d',' -f1)
	else
		remote=$REMOTE
	fi

	if [ "X$remote" = "X" ]
	then
		mylog "warning: skipping user $user, no remote defined"
		continue
	fi

	if $F_EXEC
	then
		mylog "running: $RunCmd $DebugFlag $user $remote"
		$RunCmd $DebugFlag $user $remote 2>&1 || status=$?
	else
		mylog "(dummy) running: $RunCmd $DebugFlag $user $remote"
	fi
done

mylog "== end"
exit $status
