. /usr/syno/bin/jsoncmd

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

DB_VERSION=$(cat ${SYNOPKG_PKGPATH}/target/conf/db_version.json)
VERSION=$(jget "${DB_VERSION}" ".app_data_version")

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

TMP_DB=$(jget "${SYNOPKG_BKP_INPUT}" ".external_handler_result[0].result[0].db_temp_name")
if [ $? -ne 0 ];then
	logger -p 0 "cannot find temp database"
    exit 1
fi

/bin/killall synoscgi_SYNO.Cal.InviteMail_1_reply
sudo -u postgres psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND datname='calendar';"
sudo -u postgres psql -c "DROP DATABASE calendar"
if [ $? -ne 0 ];then
    logger -p 0 "cannot drop database calendar"
    exit 1
fi

sudo -u postgres psql -c "ALTER DATABASE ${TMP_DB} RENAME TO calendar"
if [ $? -ne 0 ];then
    logger -p 0 "cannot rename database ${TMP_DB} -> calendar"
    exit 1
fi

sudo -u postgres psql -c "ALTER DATABASE calendar OWNER TO \"synocalendar\""
if [ $? -ne 0 ];then
    logger -p 0 "cannot alter database calendar owner to synocalendar"
    exit 1
fi

# create new table, and new added column
${SYNOPKG_PKGPATH}/target/tool/syno_initialize_db_schema.sh >> /var/log/synocal.log 2>&1

importPath=$(jget "${SYNOPKG_BKP_INPUT}" ".temp_path")
if [ $? -ne 0 ];then
		logger -p 0 "no temp path"
        jerr "bad parameters"
        exit 1
fi

if [ -e ${importPath}/cal_sharing_db.txt ]; then
	logger -p 0 "/usr/syno/bin/synosharingbackup --mode restore --drop --file ${importPath}/cal_sharing_db.txt --project_name=SYNO.Cal.Application"
	/usr/syno/bin/synosharingbackup --mode restore --drop --file ${importPath}/cal_sharing_db.txt --project_name=SYNO.Cal.Application
fi

strBasePath=`${SYNOPKG_PKGPATH}/target/tool/synocalendar --attach-base-path-get`
if [ $? -eq 0 ] && [ -d ${strBasePath} ] && [ -d ${importPath}/attach ];then
	logger -p 0 "cp -rf ${importPath}/attach/* ${strBasePath}/"
	cp -rf ${importPath}/attach/* ${strBasePath}/
fi
jdone

exit 0
