#!/bin/bash
# VERSION=5
# CHANGES="script used as backup. must be removed in  the future"

###########
## /!\ /!\ PLEASE DO NOT USE THIS SCRIPT /!\ /!\
##
## USE /etc/init.d/S65cloud INSTEAD 

BEROCONF="/usr/fallback/beroconf"

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

function start () {
	# if cloud disabled, leave
	if [ "$(${BEROCONF} get root cloud_enable | grep -v failed)" != "1" ]; then
		log "Disabled."
		exit 0
	fi

	# if a cron-job for cloud-api is already defined, remove it
	if [ ! -z "$(crontab -l | grep cloud-api)" ]; then
		crontab -l | grep -v cloud-api > /tmp/crontab.cloud
		crontab /tmp/crontab.cloud
		rm -f /tmp/crontab.cloud
	fi

	# get the interval for the cron-job (in minutes)
	job_interval=$(${BEROCONF} get root cloud_interval | grep -v failed)
	if [ -z "${job_interval}" ]; then
		job_interval=2
	fi

	# save current crontab
	crontab -l > /tmp/crontab.cloud

	# add cloud-api-entry
	echo "*/${job_interval} * * * * /usr/local/bin/cloud-api" >> /tmp/crontab.cloud

	# apply changes
	crontab /tmp/crontab.cloud
	rm -f /tmp/crontab.cloud

	log "Started."
}

function stop () {

	# remove cloud-api from crontab
	crontab -l | grep -v cloud-api > /tmp/crontab.cloud
	crontab /tmp/crontab.cloud
	rm -f /tmp/crontab.cloud

	log "Stopped."
}

case "${1}" in
	start)
		## check the cloud from rootfs is not running
		if [ ! "$(crontab -l | grep cloud)" = "" ]; then
			exit 0
		fi
		## annoying. cloud from rootfs not running. using the backup
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 1
		start
		;;
	*)
		echo "Usage: ${0} [start|stop|restart]" >&2
		exit 1
		;;
esac

exit 0
