#!/bin/bash

function usage {
	echo "usage: $(basename $0) start <config file>"
	echo "usage: $(basename $0) stat <config file>"
	echo "usage: $(basename $0) stop <config file>"
}


function start_worker {
	# each worker creates a log in $log_path/worker.$profile.N where N is a number that increments for each worker
	# that's started. N should start at 1 and increments to the next highest value available. 

	n=`ls -l ${log_path}/ | grep worker.${profile} | awk '{print $NF}' | awk -F. '{print $NF}' | tail -1`
	n=$((n + 1))
	echo "Starting worker $n from $broker_jar"
	logfile=${log_path}/worker.${profile}.${n}
	touch $logfile

	java -Xms512m -Xmx3g -d64 -classpath $broker_jar org.genemania.broker.Worker >> $logfile 2>&1 &
}


# check if workers are running. Returns 0 if true, 1 if false.
function check_status {
	err=0

	workers_pid=`ps aux | grep ${broker_jar} | grep Worker | grep -v grep | awk '{print $2 " "}' | tr -d '\n'`
	if [[ ! -z ${workers_pid} ]]; then 
		cd $log_path
		active=`ls -latr worker.${profile}.* 2> /dev/null | awk '{print $NF}' | tail -1`

		echo "Worker PID: ${workers_pid}"
		echo "Last active worker: ${active}"
	else
		echo "Worker not running." 
		err=1
	fi
	return ${err}
}


########
# main #
########

if [[ $# -lt 2 ]]; then
	usage
	exit 1
fi

start=0
stop=0
status=0
config=""

if [[ $1 == 'start' ]]; then 
	start=1
elif [[ $1 == 'stop' ]]; then
	stop=1
elif [[ $1 == 'stat' ]]; then
	status=1
else
	usage
	exit 1
fi

config=$2
if [[ -z $config || ! -r $config ]]; then
	echo "[ERROR] Cannot read $config"
	exit 1
fi

source $config

# export JAVA_HOME to the one specified in the config file
export JAVA_HOME=${JAVA_HOME}
echo "JAVA_HOME: $JAVA_HOME"

if [[ $start -eq 1 ]]; then
	for (( i=0; i<$start_workers; i++ )); do 
		start_worker
	done

elif [[ $stop -eq 1 ]]; then
	archivedir=`date "+%Y%m%d"`
	timestamp=`date "+%Y%m%d.%H%M%S"`

	# stop workers for this profile
	pids=`ps aux | grep ${profile}-broker | grep -v grep | awk '{print $2}'`
	kill -9 $pids > /dev/null 2>&1
	#kill -3 $pids 

	ps aux | grep ${profile}-broker | grep -v grep | awk '{print $2}'
	if [[ $? -eq 0 ]]; then 
		pushd $log_path 2>&1 > /dev/null
		for i in worker.${profile}.*; do
			if [[ -e $i ]]; then 
				mkdir -p ${archivedir}
				mv $i ${log_path}/${archivedir}/${i}.${timestamp}
				echo "Saved $i to ${archivedir}"
			fi
		done
		popd 2>&1 > /dev/null

		printf "Stopped workers. PIDs: "
		echo $pids
	else
		if [[ -z $pids ]]; then
			echo "There are no workers running."
		else
			printf "Could not stop workers. PIDs: "
			echo $pids
		fi
	fi
elif [[ $status -eq 1 ]]; then 
	check_status
fi
