#!/bin/bash

BASE_DIR=`pwd`
prog_file=$1
shift

echo -n 0 > ${prog_file}

# Data type hot/cold/mix
if [ -z "$1" ]
then
        MODE=mix
else
        MODE=$1
fi

DATE=`date +"%b-%d-%Y-%H-%M"`

# Location of the  "encoder simulator" binary
SPORT=/opt/rbt/bin/encoder_simulator
if [ ! -f "$SPORT" ]
then
	echo "$SPORT not found."
	exit 1
fi
#SPORT=/var/encoder_simulator

# which XML config file to use.
# Can be "/var/home/root/enc_scripts/basic_config.xml"
if [ ! -f /var/etc/opt/tms/output/configfile.xml ]
then
        echo "configfile.xml not found."
        exit 1
fi
cp /var/etc/opt/tms/output/configfile.xml /tmp/test_config.xml
# If there is no VBASE, we need to give a valid sport ID
sed -i 's/sport id="0"/sport id="1"/g' /tmp/test_config.xml
XML=/tmp/test_config.xml

# Hard coded "simulate encoder" config file.
SIM=/tmp/simulate_encoder_splice

# How long to wait after starting the test, to be in 
# stable mode. E.g. wait until the cold phase is done for 'hot' data.
# Needed long wait depending of hot, warm and mix sizes.
SLEEP_AFTER_START=120
# How long to run (in seconds)
if [ -z "$2" ]
then
        OP_RUN_TIME=300
else
        OP_RUN_TIME=$2
fi

# Location of the directory where script-sum is located

if [ -z "$3" ]
then
    SCRIPT_LOC=/opt/rbt/bin/palperf/palperf_test_simencode
else
    SCRIPT_LOC=$3
fi

if [ -r /var/tmp/binaries-debug/vmlinux-smp ] 
then
	VMLINUX=" --vmlinux=/var/tmp/binaries-debug/vmlinux-smp "
else
	VMLINUX=" --no-vmlinux "
fi

CACHEPGS=`cat $XML | grep "cachepgs=" | tr '"' ' ' | awk '{print $2}'`
PAGE_SIZE=$((8*1024))

##################################################################################

# Some default settings....
SPLICE=200
CLUSTER=131072
DATA_TYPE=34
REPORT_TIME=10
SIZE=-1
READ_MIX=0
WRITE_MIX=0
DO_SDR=1
DO_COMP=1
IN_MEM_ONLY=1
DIRTY_PAGE_HWM=105
QLEN_HWM=5


##################################################################################

# Some internal settings, to collect summary info
# and eliminate beginning and ending data points.

RUNTIME=${OP_RUN_TIME}
STATS_INTERVAL=10

DATA_STT=`echo "${RUNTIME} / ${REPORT_TIME}" | bc`
DATA_SDR=`echo "${RUNTIME} / ${STATS_INTERVAL}" | bc`
DATA_TOP=`echo "${RUNTIME} / ${STATS_INTERVAL}" | bc`

# Assume about 200 Mbps per splice 
TPUT_PER_SPLICE=200000000
TPUT_CAP_SPLICE=8


AUX_NAME=""
PROFILER=""
SLEEP_BETWEEN_INTERVALS=1

##################################################################################

# The real test loop

DATE=`date +"%b-%d-%Y-%H-%M"`

# Some internal estimate, to adapt the SLEEP_AFTER_START
# And shorten the wait time
if [ ${SPLICE} -gt ${TPUT_CAP_SPLICE} ]
then
	TPUT_SPLICE_CNT=${TPUT_CAP_SPLICE}
else
	TPUT_SPLICE_CNT=${SPLICE}
fi

case ${MODE} in
	cold )
	SIZE=-1
	READ_MIX=0
	WRITE_MIX=0
	DO_COMP=1
	NAME1=cold-
	SLEEP_AFTER_START=120
	;;
        cold_sdr )
	SIZE=-1
	READ_MIX=0
	WRITE_MIX=0
	DO_COMP=0
	NAME1=cold-sdr-only-
	SLEEP_AFTER_START=61
	;;
	warm_sdr )
	SIZE=30000000000
	READ_MIX=0
	WRITE_MIX=0
	DO_COMP=0
	NAME1=warm-sdr-only-
	SLEEP_AFTER_START=`echo "120 + ( ${SIZE} * 8 /  ${TPUT_PER_SPLICE} / ${TPUT_SPLICE_CNT} ) " | bc`
	;;
	warm )
	SIZE=30000000000
	READ_MIX=0
	WRITE_MIX=0
	DO_COMP=1
	NAME1=warm-
	SLEEP_AFTER_START=`echo "120 + ( ${SIZE} * 8 /  ${TPUT_PER_SPLICE} / ${TPUT_SPLICE_CNT} ) " | bc`
	;;
	hot )
	SIZE=$(( (($CACHEPGS*$PAGE_SIZE)) /100)) # Setting size 100 times smaller than cache memory so that traffic will be hot.
	READ_MIX=0
	WRITE_MIX=0
	DO_COMP=1
	NAME1=hot-
	SLEEP_AFTER_START=`echo "120 + ( ${SIZE} * 8 /  ${TPUT_PER_SPLICE} / ${TPUT_SPLICE_CNT} ) " | bc`
	;;
	mix )
	SIZE=$(( (($CACHEPGS*$PAGE_SIZE)) / 2)) # Set size parameter roughly 50% of the cache memory for mix traffic.
	READ_MIX=2
	WRITE_MIX=1
	DO_COMP=1
	NAME1=mix-
	SLEEP_AFTER_START=`echo "120 + ( ${SIZE} * 8 /  ${TPUT_PER_SPLICE} / ${TPUT_SPLICE_CNT} ) " | bc`
	;;
	mix_sdr )
	SIZE=120000000000
	READ_MIX=2
	WRITE_MIX=1
	DO_COMP=0
	NAME1=mix-sdr-only-
	SLEEP_AFTER_START=`echo "120 + ( ${SIZE} * 8 /  ${TPUT_PER_SPLICE} / ${TPUT_SPLICE_CNT} ) " | bc`
	;;
esac

NAME=`basename ${SPORT}`-${AUX_NAME}${NAME1}splice-${SPLICE}-d-${DATA_TYPE}-page-${CLUSTER}-${DATE}


# OK, all settings done
# Create ${SIM} file

echo "#   /tmp/simulate_encoder_splice
# splice_count
${SPLICE}
# cluster_size in bytes
${CLUSTER}
# data_type: 4 (rnd), 8 (cnt), 9 (all 0), 30 (64 bit '0', '1'), 34 (no data) 
${DATA_TYPE}
# report_time in sec
${REPORT_TIME}
# data_length in bytes (use -1 for cold)
${SIZE}
# data_pos_init  (default 0)
0
# read_mix
${READ_MIX}
# write_mix
${WRITE_MIX}
# do_sdr:  0: false, 1: true, default: 1
${DO_SDR}
# do_comp:  0: false, 1: true, default: 1
${DO_COMP}
# in_mem_only:  0: false, 1: true, default: 0
${IN_MEM_ONLY}
# dirty_pages_hwm (stop generating data when X % of pages are dirty)
${DIRTY_PAGE_HWM}
# qlen_hwm (similar as max txn, default 5)
${QLEN_HWM}
#
" > ${SIM}

if [ -f /var/log/sdr.stats ]; then
    rm /var/log/sdr.stats
fi

echo "# `date` # START:   ${SPORT} -c ${XML} > log-${NAME}" > /tmp/log-${NAME}

${SPORT} -c ${XML} >> /tmp/log-${NAME} 2>&1 &

SPORT_BIN=`basename $SPORT`


# Function to stop simulator process when script terminated unexpectedly
function clean_up {
	kill -SIGINT `pidof  ${SPORT_BIN}`
	sleep 10
	if [ "xx`pidof ${SPORT_BIN}`" != "xx" ]
	then
		kill -SIGKILL `pidof  ${SPORT_BIN}`	
	fi
	rm -f /tmp/log-${NAME}
	rm -f ${SIM}
	exit 1
}

# Calling the bookeeping function on receiving termination signal
trap clean_up SIGHUP SIGINT SIGTERM
	
TOT_DATA_RCVD=0
SLEEP_BETWEEN_CHECKS=`expr $STATS_INTERVAL / 3`       
        
while [ ! -e /var/log/sdr.stats ]
do
	sleep $SLEEP_BETWEEN_CHECKS
#      echo "**** Waiting for sdr stats file to be created ****"
done

echo -n 10 > ${prog_file}

while [ $TOT_DATA_RCVD -lt $SIZE ]
do
	sleep $SLEEP_BETWEEN_CHECKS
	TOT_DATA_RCVD=`cat /var/log/sdr.stats | grep "tot_enc_bytes_in " | awk '{print $2;}' | ${SCRIPT_LOC}/script-sum.sh | awk '{printf "%ld", $4}'`
 #      echo "**** LAN DATA processed : $TOT_DATA_RCVD **** "
done        

echo -n 20 > ${prog_file}

progress=20
interval_time=$(( ${OP_RUN_TIME} / 16 ))
per_inter_prog=$(( 80/16 ))
for i in `seq 1 16`; do
    sleep ${interval_time}
    progress=$(( ${progress} + ${per_inter_prog} ))
    echo -n ${progress} > ${prog_file}
done

kill -SIGINT `pidof  ${SPORT_BIN}`

sleep 10
while [ "xx`pidof ${SPORT_BIN}`" != "xx" ]
do
	echo "wait for shutdown of ${SPORT_BIN}" >> /tmp/log-${NAME}
	sleep 10
done

STT_TPUT=`grep "currently: " /tmp/log-${NAME} | tail -${DATA_STT} | awk '{print $9}' | ${SCRIPT_LOC}/script-sum.sh`
STT_TPUT_AVG=`echo "${STT_TPUT}" | awk '{print $6}'`
#        echo "# STT_TPUT = ${STT_TPUT} "

echo -n 100 > ${prog_file}
echo "${STT_TPUT_AVG}"
   
