#!/bin/bash

##################################
#  @program        smon
#  @description    simulation monitor
#  @copyright      Copyright “(c)2009 Centre National de la Recherche Scientifique CNRS. 
#                             All Rights Reserved”
#  @svn_file       $Id: failover 2545 2013-02-01 09:58:10Z jripsl $
#  @version        $Rev: 2545 $
#  @lastrevision   $Date: 2013-02-01 10:58:10 +0100 (Fri, 01 Feb 2013) $
#  @license        CeCILL (http://dods.ipsl.jussieu.fr/jripsl/smon/LICENSE)
##################################

# Notes
#   - bash required version: 3+
#   - "=" and " " are used as delimiter in scenario file (be sure note to use it in fields data)

# init

send_msg_cmd="/home/jripsl/snapshot/Monitoring/CNClient/sendAMQPMsg"
g__stackfile=
g__scenario_dir=scenario
g__mode="scenario"
g__scenariofile=
g__dryrun=0
g__confirm=0
g__delay=1 # delay between message

# func

curdate ()
{
    date '+%F %T'
}

msg ()
{
    l__code="$1"
    l__msg="$2"

    echo "$(curdate) - $l__code - $l__msg"
}

usage ()
{
	cat >&1 << EOF

USAGE: $(basename $0) [-m mode] [-s scenario] [-l] [-t file]

OPTIONS:
   -c              ask for confirmation
   -h              this help
   -f              set stack file
   -l              print scenarios list 
   -m              set MODE
                   MODE may be "scenario", "stackfile" or "cleanup"
                   default mode is "scenario"
   -s              set scenario file

EXAMPLES:

   To parse a stack file and send corressponding messages, do:

   $0 -m stackfile -f ../sample/stack_light

   To list scenarios, do:

   $0 -l

   To run scenario <scenario>, do:

   $0 -s <scenario>
EOF
	exit 2
}

list_scenarios ()
{
	echo ""
	echo "Scenarios list:"
	echo ""
	ls -1 $g__scenario_dir
	echo ""
	exit 2
}

send_cleanup_msg()
{
	$send_msg_cmd -h localhost -p 5672 -b "$( echo {\"code\":\"8888\"} | base64 -w 0 )"
}

# check

if [ $# -eq 0 ]; then
	usage
fi

# parse args

while getopts 'cdf:hlm:s:' OPTION
do
  case $OPTION in
  c)    g__confirm="1"
        ;;
  d)    g__dryrun="1"
        ;;
  f)    g__stackfile="$OPTARG"
        ;;
  h)    usage
        ;;
  l)    list_scenarios
        ;;
  m)    g__mode="$OPTARG"
        ;;
  s)    l__scenariofile="$OPTARG"

		if [[ "$l__scenariofile" =~ "*/*" ]]; then
			# full/relative path was given with the filename

			g__scenariofile="$l__scenariofile"
		else
			# only the filename was given

			g__scenariofile="$g__scenario_dir/$l__scenariofile"
		fi

		;;
  ?)    exit 1 # we come here when a required option argument is missing (bash getopts mecanism)
        ;;
  esac
done

# mode switch
if [ "$g__mode" = "scenario" ]; then

	# check
	if [ ! -f "$g__scenariofile" ]; then
		msg "LIBIGCM-MOCK-ERR003" "scenario file not found ($g__scenariofile)"
		exit 1
	fi

	while read LINE <&3; do

		# debug
		#echo $LINE

		l__JSON_msg_buf=
		N=1
		fields_arr=(${LINE// / }) # process fields (split on " " delimiter)
		for FIELD in "${fields_arr[@]}"; do

			# debug 
			#echo $FIELD


			field_arr=(${FIELD//=/ }) # process key/value (split on "=" delimiter)
			key=${field_arr[0]}


			# HACK
			if [ "$key" = "file" ]; then
				# special processing for "file" key (base64 encoding)

				l__configcard_file="/home/jripsl/snapshot/Monitoring/sample/${field_arr[1]}"

				# check
				if [ ! -f "$l__configcard_file" ]; then
					msg "LIBIGCM-MOCK-ERR004" "config-card file not found ($l__configcard_file)"
					exit 1
				fi

				val=$( cat $l__configcard_file | base64 -w 0 )

			else
				val=${field_arr[1]}
			fi


			# append to JSON message buffer
			if [ "$N" -gt "1" ]; then

				l__JSON_msg_buf="$l__JSON_msg_buf,\"$key\":\"$val\""
			else
				# first field

				l__JSON_msg_buf="\"$key\":\"$val\""
			fi


			N=$((N+1))
		done

		# enclose
		l__JSON_msg_buf="{""$l__JSON_msg_buf""}"

		# debug
		#echo $l__JSON_msg_buf

		# message base64 encoding
		l__JSON_msg_buf_encoded=$( echo $l__JSON_msg_buf | base64 -w 0 )

		# debug
		#echo $l__JSON_msg_buf_encoded
		#echo $send_msg_cmd -h localhost -p 5672 -b "$l__JSON_msg_buf_encoded"

		# send AMQP message
		if [ "$g__dryrun" = "1" ]; then

			echo $send_msg_cmd -h localhost -p 5672 -b "$l__JSON_msg_buf"


			# debug
			#
			# uncomment line below (and comment line above) to output only the encoded message
			# 
			# it can then be unencoded for debug purpose (message encoding level, not config-card encoding) using command below
			# ./libIGCM_mock.sh -s start_simu__stop_simu -d | base64 -d | less
			# 
			# 
			#echo $l__JSON_msg_buf_encoded

		else
			$send_msg_cmd -h localhost -p 5672 -b "$l__JSON_msg_buf_encoded"
		fi




		if [ "$g__confirm" = "1" ]; then
			read -p "<<< $l__JSON_msg_buf >>>> sent. Press enter for next message" bla
		else
			echo "<<< $l__JSON_msg_buf .>>>>"
			sleep $g__delay
		fi



		# debug
		#break

	done 3<$g__scenariofile

elif [ "$g__mode" = "cleanup" ]; then

	send_cleanup_msg

elif [ "$g__mode" = "stackfile" ]; then

	# check
	if [ ! -f $g__stackfile ]; then
		msg "LIBIGCM-MOCK-ERR001" "file not found"
		exit 1
	fi

	IFS=$'\n'
	for line in $(cat $g__stackfile); do
		#echo $line | awk -F" " '{print $4}'
		callname=$(echo $line | awk -F" " '{print $4}' )
		$send_msg_cmd localhost 5672 string "$callname"
	done
else
	msg "LIBIGCM-MOCK-ERR002" "incorrect mode"
	exit 1
fi

exit 0
