#!/bin/bash

. ${TOOLKIT}-functions.sh

# this must be done early, or packages install will fails
#
[ -f /etc/apt/sources.list.d/veeam.list ] || {

	install_pkgs veeam-release-deb
	update_repos
}


# sanity checks for v13
#
kusa-conf veeam-agent.maxpoints >/dev/null 2>/dev/null && {
	echo -e "\nERROR: MaxPoints is deprecated in Veaam V13, you need to"
	echo -e "replace it with MaxDays (converting as needed, bases on"
	echo -e "backup scheduling)\n"
	exit 1
}


# randomize cron runs?
#
getconfirm veeam-agent.randomize_cron_runs && {
	# we record randomized value in permanent file, instead of using
	# transient local-db $MODLOCALDB, so multiple kusa-reconf invocations
	# will be coherent

	cfgfile="/etc/kusa/conf.d/zz-veeam-agent-randomize.cfg"

	echo

	if [ -f $cfgfile ]
	then
		echo " veeam-agent: RANDOM value for cronjob minutes invocation"
		echo "	already recorded in $cfgfile"
	else
		# we must work on veeam-agent.cron_time entry in kusa db, can be
		# customized by user
		#
		cron_time=$(jtconf veeam-agent.cron_time)

		# replaces first token (minutes) with a random one
		#
        	minutes=$((RANDOM%60))
		cron_time=$(echo "$cron_time" | sed -e 's/^[^ ][^ ]* //')
		cron_time="$minutes $cron_time"

		# overrides kusa db entry
		#
		(
			echo "# $cfgfile"
			echo "#"
			echo "# do not modify!"
			echo "# automatically created by 'run-pre' script of 'veeam-agent' kusa module"
			echo "#"
			echo "# remove me if you want to recalculate random cron time"
			echo "#"
        		echo "[veeam-agent]"
        		echo "  cron_time	$cron_time"
			echo
			echo "# (eof) $cfgfile"
		) >$cfgfile

		echo " veeam-agent: RANDOM value for cronjob minutes invocation: $minutes"
		echo "	recorded in $cfgfile"
	fi

	echo "  remove this file if you want to recalculate it"
	echo
}

exit 0
