#!/bin/bash

DEBUG="${1}"
LOGFILE="/tmp/sigfix.log"
CURRENT_VERSION=""
NEW_VERSION=""

function LOG()
{
	if [ "${DEBUG}" = "Y" ]; then
		echo "[$(date +%T-%D)]${1}" >> "${LOGFILE}"
	fi
}

function wait_for_update()
{
	if [ -z "${CURRENT_VERSION}" ]; then
		LOG "Could not get current signature version. Waiting 10 minutes for update to finish."
		sleep 600
	else
		NEW_VERSION=$(grep Version /opt/BitDefender/var/lib/scan/base/Plugins/update.txt | cut -d " " -f2)
		while [ "${NEW_VERSION}" = "${CURRENT_VERSION}" ]; do
			LOG "New version is still: ${NEW_VERSION}. Waiting 60 seconds and checking again"
			sleep 60
			NEW_VERSION=$(grep Version /opt/BitDefender/var/lib/scan/base/Plugins/update.txt | cut -d " " -f2)
		done
	fi
	LOG "New downloaded version: ${NEW_VERSION}"
	sleep 60
}

function check_services()
{
	/opt/BitDefender/bin/bd-sve-client status | grep bdsrvscand | grep dead &> /dev/null
	if [ $? -eq 1 ]; then
		LOG "BitDefender Scan Daemon is not dead."
		exit -2
	fi
}

function get_current_version()
{
	if [ -f "/opt/BitDefender/var/lib/scan/update.xml" ]; then
		LOG "Getting current version from update.xml"
		CURRENT_VERSION=$(grep first /opt/BitDefender/var/lib/scan/update.xml | cut -d '"' -f4) || true
	else
		LOG "File update.xml does not exist. Getting current version from base/Plugins/update.txt"
		CURRENT_VERSION=$(grep Version /opt/BitDefender/var/lib/scan/base/Plugins/update.txt | cut -d " " -f2)
	fi
	LOG "Current version: ${CURRENT_VERSION}"
}

function check_script_requirements()
{
	LOG "Checking script requirements"
	if [ ! -d "/opt/BitDefender" ]; then
		LOG "Bitdefender is not installed in /opt/BitDefender"
		exit -1
	fi
	get_current_version
	check_services
}

LOG 'Script started'
check_script_requirements

LOG "Starting signature update"
/opt/BitDefender/bin/bdsafe live forceupdate

LOG "Waiting for update to finish"
wait_for_update

LOG "Running bdsrvscand -k"
/opt/BitDefender/bin/bdsrvscand -k

LOG "Removing antivirus_X"
rm -rf /opt/BitDefender/var/lib/scan/antivirus_*

LOG "Removing update.xml"
rm -f /opt/BitDefender/var/lib/scan/update.xml

LOG "Restarting services"
/opt/BitDefender/bin/bd-sve-client restart

LOG "Finished"
