#!/bin/sh

#
# task_ctrl.sh
#
#   Tool to run commands list in files under /var/
#     Task filename format is /var/$task_owner.ID
#
# Copyright (C) 2013  Bayram Kurumahmut <bayram.kurumahmut@airties.com>
#

exe_name=`echo ${0##*/}`

sleep_time=5
sleep_time_tr069=15

. /usr/bin/debug.sh

debug_level=5
debug_owner=$exe_name
debug_logfile=/var/$debug_owner.log

. /usr/bin/config.sh

resp_type="onlyresp"
try_val="try 5"
req_val=$exe_name

usage()
{
	echo "
Usage: $exe_name -t TASK_OWNER [-s SLEEP_TIME]
  TASK_OWNER    : probably an instance ID ex. hotspot-0
  SLEEP_TIME    : sleep time between new task checks (default $sleep_time)

  What does this script do?
    - Runs forever in a while loop
    - Check if there are files, having format of '{TASK_OWNER}.task.{ID}', located under /var
    - If there is, we know that each file has only 1 line of command waiting to be executed
    - Therefore, we execute these commands in order (which is alphabetical)
"
}

#
# Parse command line arguments
#

while [ "$1" != "" ]
do
    case "$1" in
	-h)
	    shift;
	    usage
	    exit;;
	-t)
	    shift;
	    task_owner="$1";;
	-s)
	    shift;
	    sleep_time="$1";;
	*)
	    usage
	    exit;;
    esac
    shift
done

[ ! -n "$task_owner" ] && {
	usage
}

debug_logfile=/var/${debug_owner}-$task_owner.log

dualimage_check()
{
	while [ true ]
	do
		[ `ps | grep -c dualima[g]e` = 0 ] && {
			break
		}
		debug_trace "Waiting dual image..."
		sleep $sleep_time
	done
}

mngr_check()
{
	while [ true ]
	do
		is_mngr_started=`cli query onlyresp requester $exe_name sysmgr-0:is_mngr_started`
		[ "$is_mngr_started" = "1" ] && {
			break
		}
		debug_trace "Waiting mngr start..."
		sleep $sleep_time
	done
}

tr069_check()
{
	while [ true ]
	do
		initial_time_elapsed=`cli query onlyresp requester $exe_name tr069-0:initial_time`
		[ "$initial_time_elapsed" = "1" ] && {
			break
		}
		debug_trace "Waiting tr069 initial time..."
		sleep $sleep_time_tr069
	done
}

run_list()
{
	count=2
	while [ $count -gt 0 ]
	do
		for task in `ls /var/$task_owner.task.* 2>/dev/null`
		do
#			tr069_check
			cmd=`cat $task`
			debug_trace "Running $task => $cmd"
			rm -rf $task
			eval "$cmd"
			debug_trace "Finished $task => $cmd"
		done
		count=$(( count - 1 ))
		sleep 1
	done
}

call_apply()
{
	[ -f $apply_list_file ] && {

		debug_trace "task_list:$(ps | grep hotspo[t].sh)"

		for apply_inst in `cat $apply_list_file | sort | uniq`
		do
			cli_cmd "$apply_inst:apply"
		done

		rm -f $apply_list_file
	}
}

while [ true ]
do
	dualimage_check

	mngr_check

	run_list

	call_apply

	sleep $sleep_time
done
