#!/bin/bash
#
# VERSION=4
# CHANGES="Added a parameter to setup crontab-entry only."

export PATH=${PATH}:/sbin/:/bin:/usr/sbin:/usr/bin:/usr/fallback

BEROCONF=/usr/fallback/beroconf

function log () {
	echo "[init_provisioning] ${1}"
}

function setup_cron () {
	# get the polling interval
	polling_interval=$(${BEROCONF} get root polling_interval | grep -v failed)

	# if it is not set, we do not add crontab-entry
	if [ -z "${polling_interval}" ]; then
		/usr/bin/crontab -l | grep -v provisioningTool.php > /tmp/prov_cron.tmp
		/usr/bin/crontab /tmp/prov_cron.tmp
		rm -f /tmp/prov_cron.tmp
		return
	fi

	log "Adding crontab-entry with interval of ${polling_interval} minutes."

	# add entry into crontab
	/usr/bin/crontab -l | grep -v provisioningTool.php > /tmp/prov_cron.tmp
	# add cron-job if it is set
	if [ ! -z "${polling_interval}" ] && [ "${polling_interval}" != "0" ]; then
		echo "*/${polling_interval} * * * * /usr/bin/env -i bash -c \"/usr/php/provisioningTool.php config\"" >> /tmp/prov_cron.tmp
	fi
	/usr/bin/crontab /tmp/prov_cron.tmp
	rm -f /tmp/prov_cron.tmp
}

function start_prov () {
	log "Running BootUp-Provisioning."
	/usr/bin/env -i bash -c "/usr/php/provisioningTool.php config firmware" > /dev/null
}

# do not start if this card needs to be produced
if [ "$(${BEROCONF} get root need_prod | grep -v failed)" = "1" ]; then
	exit 0
fi

# do not start if this card is in recovery-mode
if [ "$(${BEROCONF} get root boot_recoverymode | grep -v failed)" = "1" ]; then
	exit 0
fi

# do not start of this card is factory-resetted
if [ -f /sys/class/beronet/gateway/resetjumper ] && [ "$(cat /sys/class/beronet/gateway/resetjumper)" = "1" ]; then
	exit 0
fi

# do not start if this card is in update-mode
if [ "$(${BEROCONF} get root boot_fwupdate | grep -v failed)" = "1" ]; then
	exit 0
fi

case "${1}" in
	start)
		setup_cron
		start_prov
		;;
	cron_setup)
		setup_cron
		;;
	*)
		echo "Usage: ${0} [start|cron_setup]" >&2
		exit 1
		;;
esac

