#!/bin/sh

usage()
{
	echo "Restore settings for all mailboxes."
	echo "Usage: $prog [OPTION]"
	echo ""
	echo "OPTIONS:"
	echo "  --without-spam   restore all settings except for SpamAssassin configuration"
	echo "  --with-spam      restore all settings"
	echo "  --spam-only      restore only SpamAssassin settings"

	exit 0
}

exec_util()
{
	local progname="$1"
	shift
	local args="$*"

	echo -n "==> Checking for: ${progname##*/}... "

	if [ -x "$progname" ]; then 
		$progname $args 1>$log_file 2>&1

		if [ "$?" -ne "0" ]; then
			err_utils_list="$err_utils_list $progname"
			echo "fail"
			return 1
		else 
			echo "ok"
		fi
	else
		echo "not exists"
		return 1
	fi

	return 0
}

check_status()
{
	if [ -n "$err_utils_list" ]; then
		echo "Errors occured in mail restore procedure"
		echo "Some utilities was exited with errors:"

		for util in $err_utils_list; do
			echo "  $util"
		done

		[ -f "$pid_file" ] && rm -f $pid_file
		exit 1
	fi
}

export LANG="C"
export LC_ALL="C"

err_utils_list=""
restore_utils_dir="/usr/lib/plesk-9.0"
log_file="/tmp/mchk.log"
pid_file="/var/run/mchk.pid"

prog="$0"

with_spam=0
with_all=1

if [ -f "$pid_file" ]; then
	echo "$prog already running"
	exit 1
fi

if [ -n "$1" ]; then
	case "$1" in
		*spam-only)
			with_all=0
			with_spam=1
			;;
		*with-spam)
			with_spam=1
			;;
		*without-spam)
			with_spam=0
			;;
		-v)
			with_spam=1
			;;
		*help|-h)
			usage
			;;
		*)
			echo  "ERROR: option $1 is not valid"
			echo  ""
			usage
			;;
	esac
fi

# spamassassin restore
if [ $with_spam -eq 1 ]; then
	exec_util $restore_utils_dir/mail_spam_restore
fi

if [ $with_all -eq 1 ]; then
	exec_util $restore_utils_dir/mailsrv_conf_init || exit 1

	# restore mailboxes
	exec_util $restore_utils_dir/mail_mailbox_restore

	# restore MTA database and configs
	exec_util $restore_utils_dir/mailsrv_entities_dump

	# aliases restore
	exec_util $restore_utils_dir/mail_admin_aliases

	# authentication DB restore
	exec_util $restore_utils_dir/mail_auth_dump

	# MailLists restoration
	exec_util $restore_utils_dir/mailman_lists_dump

	# autoresponder restore
	exec_util $restore_utils_dir/mail_responder_restore

	# drweb restore
	exec_util $restore_utils_dir/mail_drweb_restore

	# kav restore
	exec_util $restore_utils_dir/mail_kav_restore

	# spf restore
	exec_util $restore_utils_dir/mail_spf_restore

	# dk restore
	exec_util $restore_utils_dir/mail_dk_restore

	# greylisting restore
	exec_util $restore_utils_dir/mail_grey_restore

	# courier auth restore
	courier_restart=0
	for conf in pop3d pop3d-ssl imapd imapd-ssl; do
		/opt/psa//admin/bin/courier_authpsa_configure "$conf" add
		[ "$?" -ne 110 ] || courier_restart=110
	done
	[ "$courier_restart" -ne 110 ] || /etc/init.d/courier-imap restart
fi

check_status

[ -f "$pid_file" ] && rm -f $pid_file

exit 0
