#!/bin/sh
. /usr/syno/bin/jsoncmd

restore_report_time()
{
	local import_path=${1}
	cat "/etc/crontab" | grep -v "/var/packages/MailServer/target/bin/syno_send_report" > "/etc/crontab.$$"

	if [ -e "${import_path}/report_time" ]; then
		cat "${import_path}/report_time" >> "/etc/crontab.$$"
	fi

	mv "/etc/crontab.$$" "/etc/crontab"
	/bin/kill -HUP `/bin/cat "/var/run/crond.pid"`
}

restore_dkim_key()
{
	local import_path=${1}

	if [ -e "${SYNOPKG_PKGPATH}/etc/dkim.key"];then
		rm -r "${SYNOPKG_PKGPATH}/etc/dkim.key"
	fi

	if [ -e "${import_path}/dkim.key" ];then
		cp -r "${import_path}/dkim.key" "${SYNOPKG_PKGPATH}/etc/dkim.key"
	fi
}

restore()
{
	local import_path=${1}
	local enable_rule_list=`cat ${import_path}/enable_rule_list`

	/bin/cp -rf ${import_path}/* ${SYNOPKG_PKGPATH}/etc/

	for rule in ${enable_rule_list}
	do
		/bin/cp ${import_path}/rules/${rule} ${SYNOPKG_PKGPATH}/target/etc/spamassassin/
	done

	restore_report_time ${import_path}
	restore_dkim_key ${import_path}

	rm ${import_path}/enable_rule_list
}

update()
{
	local major_ver=`echo "${SYNOPKG_PKGVER_ORG}" | cut -d '.' -f 1`
	local minor_ver=`echo "${SYNOPKG_PKGVER_ORG}" | cut -d '.' -f 2 | cut -d '-' -f1`
	local build_num=`echo "${SYNOPKG_PKGVER_ORG}" | cut -d '-' -f 2`
	/var/packages/MailServer/target/bin/updater -M ${major_ver} -m ${minor_ver} -v ${build_num}
}

main()
{
	local bkp_data_version=$(jget "${SYNOPKG_BKP_INPUT}" ".app_data_version")
	if [ $? -ne 0 ];then
		jerr "bad data version"
		exit 1
	fi

	$(jversion_compare ${bkp_data_version} 1.0)
	if [ $? -eq 1 ];then
		jerr "version of backup data is newer than we can handle."
		exit 1
	fi

	local import_path=$(jget "${SYNOPKG_BKP_INPUT}" ".temp_path")
	if [ $? -ne 0 ];then
		jerr "bad parameters"
		exit 1
	fi

	restore ${import_path}
	update

	exit 0
}

main

