#!/bin/bash

BEROCONF="/usr/fallback/beroconf"

case $1 in
	api)
		# if cloud disabled, leave
		if [ "$(${BEROCONF} get root cloud_enable | grep -v failed)" != "1" ]; then
			exit 0
		fi

		pid_cnt_file=/var/log/cloud.pid.cnt
		pid_old_file=/var/log/cloud.pid.old

		# get pid of still running cloup-api.php
		cloudpid_now=$(expr match "$(/bin/ps | grep 'cloud.php api' | grep -v grep)" "\([0-9]*\)")

		# if there is one, we check how long this cloud-api has been running
		if [ ! -z "${cloudpid_now}" ]; then
			# get the last recorded PID of cloud-api.php
			cloudpid_old=0
			if [ -f ${pid_old_file} ]; then
				cloudpid_old=$(cat ${pid_old_file})
			fi

			# get the times we counted a running cloud-api.php
			cloudpid_cnt=0
			if [ -f ${pid_cnt_file} ]; then
				cloudpid_cnt=$(cat ${pid_cnt_file})
			fi

			# we add to the counter this encounter with this cloud-api.php
			if [ "${cloudpid_now}" = "${cloudpid_old}" ]; then
				cloudpid_cnt=$((cloudpid_cnt + 1))
			else
				cloudpid_cnt=0
			fi

			# save values to file
			echo -n "${cloudpid_now}" > ${pid_old_file}
			echo -n "${cloudpid_cnt}" > ${pid_cnt_file}

			# until we counted the same pid 5 times (10 min),
			# we just leave without calling a new process
			if [ ${cloudpid_cnt} -lt 5 ]; then
				exit 0
			fi

			# kill the cloud that has been running for 10 minutes
			/bin/kill -9 ${cloudpid_now}
			sleep 1
		fi

		# run cloud.php
		/usr/bin/env -i bash -c "/usr/php/cloud.php api"

		# remove counter-files
		rm -f ${pid_old_file}
		rm -f ${pid_cnt_file}
		;;
	renew-ca)
		/usr/bin/env -i bash -c "/usr/php/cloud.php renew-ca"
		;;
	update)
		# check cloudFileName is defined
		if [ "$(${BEROCONF} get root cloudFileName | grep -v failed)" = "" ]; then
			exit 0
		fi
	
		# has update from cloud
		touch /tmp/hasUpdateFromCloud

		# run cloud.php
		/usr/bin/env -i bash -c "/usr/php/cloud.php update"
		;;
	*)
		echo "Usage: ${0} [api|renew-ca|update]"
		exit 1
esac

exit 0
