#!/bin/sh

PACKAGE_DEST=$SYNOPKG_PKGDEST
UPGRADE_FILE="/tmp/synoav.upgrade"

#SERVICETOOL="/usr/syno/bin/servicetool"
SYNOAV_ETC="/usr/syno/etc/packages/AntiVirus"
SCHEDULE_DB_FILE="${SYNOAV_ETC}/.schedule"
REPORT_DB_FILENAME=".report"
REPORT_DB_FILE="${SYNOPKG_PKGDEST}/${REPORT_DB_FILENAME}"
REPORT_DB_BACKUP="${SYNOPKG_PKGDEST}/../../@tmp/${REPORT_DB_FILENAME}"

# move old path report (legacy issue)
if [ -e /usr/syno/etc/packages/AntiVirus/.report ]; then
	mv /usr/syno/etc/packages/AntiVirus/.report ${REPORT_DB_FILE}
fi

if [ -e ${UPGRADE_FILE} ]; then
	# get backed up report database from previous directory
	if [ -e ${REPORT_DB_BACKUP} ]; then
		mv ${REPORT_DB_BACKUP} ${REPORT_DB_FILE}
	fi
else
	# delete report database file if not upgrade
	if [ -e ${REPORT_DB_FILE} ]; then
		rm ${REPORT_DB_FILE}
	fi
	
	# if there is report db file in tmp, recover it
	if [ -e ${REPORT_DB_BACKUP} ]; then
		mv ${REPORT_DB_BACKUP} ${REPORT_DB_FILE}
	fi
fi

# initialize AntiVirus event report database
if [ ! -e ${REPORT_DB_FILE} ]; then
	/usr/bin/sqlite3 ${REPORT_DB_FILE} < ${SYNOPKG_PKGDEST}/etc/createReportSchema.sql
fi
rm -f ${SYNOPKG_PKGDEST}/etc/createReportSchema.sql

if [ ! -e ${UPGRADE_FILE} ]; then
	# initialize and clear AntiVirus schedule scan database
	if [ -e ${SCHEDULE_DB_FILE} ]; then
		rm -f ${SCHEDULE_DB_FILE}
	fi
	/usr/bin/sqlite3 ${SCHEDULE_DB_FILE} < ${SYNOPKG_PKGDEST}/etc/createScheduleSchema.sql
	mkdir -p ${SYNOAV_ETC}/schedule/
	rm -f ${SYNOPKG_PKGDEST}/etc/createScheduleSchema.sql
fi

# initialize AntiVirus white list
if [ ! -e ${UPGRADE_FILE} ]; then
	if [ -e ${SYNOAV_ETC}/whitelist.conf ]; then
		rm ${SYNOAV_ETC}/whitelist.conf
	fi
	touch ${SYNOAV_ETC}/whitelist.conf
fi

# initialize AntiVirus extension list
if [ ! -e ${UPGRADE_FILE} ]; then
	cp ${SYNOPKG_PKGDEST}/etc/extensionlist.conf ${SYNOAV_ETC}/
	chmod 644 ${SYNOAV_ETC}/extensionlist.conf
fi

#installing the global config file
if [ ! -e ${UPGRADE_FILE} ]; then
	cp ${SYNOPKG_PKGDEST}/etc/synoav.conf ${SYNOAV_ETC}/
	chmod 644 ${SYNOAV_ETC}/synoav.conf
fi

#installing the config file of directory list of the system scan
cp ${SYNOPKG_PKGDEST}/etc/sysscanlist.conf ${SYNOAV_ETC}/
chmod 644 ${SYNOAV_ETC}/sysscanlist.conf


# link libsynoav.so to /lib/
ln -s /var/packages/AntiVirus/target/lib/libsynoav.so /lib/libsynoav.so 

# if the memory size of the DS is less than or equal to 256 MB, 
# disables database testing during the ClamAV updating process 
if [ -e /var/packages/AntiVirus/target/engine/clamav/etc/freshclam.conf ]; then
	if [ $(grep MemTotal /proc/meminfo | awk '{print $2}') -le 256000 ]; then
			sed -i "/^TestDatabases/c\TestDatabases no" /var/packages/AntiVirus/target/engine/clamav/etc/freshclam.conf
	fi
fi

exit 0
