#!/bin/bash

## BACKUP CLOUD-API FOR 21.03 FW INSTALLED WITH A 20.06 ROOTFS INSTALLED
##				( should not happen)
## PLEASE DO NOT USE THIS SCRIPT TO INCREMENT NEW CLOUD FEATURES
## USE INSTEAD THE CLOUD-API FEATURE BELONGING TO ROOTFS

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

# get pid of still running cloup-api.php
cloud_ps="$(/bin/ps | grep cloud-api.php | grep -v grep)"
cloudpid_now=$(expr match "$(echo $cloud_ps)" "\([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-api that has been running for 10 minutes
	/bin/kill -9 ${cloudpid_now}
	sleep 1
fi

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

# remove counter-files
rm -f ${pid_old_file}
rm -f ${pid_cnt_file}
