#!/bin/bash -p

# **********************************************************************
# Copyright (c) Ericsson AB 2015-2019 All rights reserved.
#
# The information in this document is the property of Ericsson.
#
# Except as specifically authorized in writing by Ericsson, the
# receiver of this document shall keep the information contained
# herein confidential and shall protect the same in whole or in
# part from disclosure and dissemination to third parties.
#
# Disclosure and disseminations to the receivers employees shall
# only be made on a strict need to know basis.
#
# **********************************************************************
#
# Rev        Date        Name        What
# -----      -------     --------    --------------------------
# 1.0        2015-04-22  egovped     Created
# 1.1        2016-03-26  eanzmagn    Minor adaptations to include in moshell
# 1.2        2017-11-04  eanzmagn    Added an extra retry when babeltrace fail to start
# 1.3        2018-06-11  eanzmagn    Increase max retry time for babelwrap from 360 to 1080 seconds
# 1.4        2018-08-29  eanzmagn    start/end time check not working on Solaris
# **********************************************************************
#

moshelldir=`dirname "$0"`
if [[ $moshelldir != /* ]] ; then moshelldir=`pwd`/$moshelldir ; fi
vobsinstallation=0
unamea=$(uname -a)
gawkext=""
if [[ $unamea = [Ll][iI][nN][uU][xX]* && $unamea = *x86_64* ]] ; then gawkext=".lin64"
elif [[ $unamea = [Ll][iI][nN][uU][xX]* && $vobsinstallation = 1 ]] ; then gawkext=".linux"
elif [[ $unamea = SunOS* && $vobsinstallation = 1 ]] ; then gawkext=".sol86"
fi

babeltrace="$moshelldir/commonjars/babeltrace${gawkext}"


live=0
count=1
first_run=1
session_id=''
babelparams="$@"

# Checking for lttng-live argument and get the session id
for var in "$@"
do
    if  [ $live -eq 1 ]
    then
        session_id=$var
        break
    fi
    if  [ "$var" == "lttng-live" ]
    then
        live=1
    fi
done

attempt=0
pre_attem=0
babeltrace_pid=-1


#Setting a trap to kill all processes
trap killgroup SIGINT

killgroup(){
  kill 0
}

##################################################################
# Method to find execution time of babeltrace command
# exit if exec time is less than 5 seconds for the first run.
#
##################################################################

cmd_exec_time () {

     end_time=$(perl -e 'print int(time)')
     diff_time=$(( $end_time - $start_time ))
     if [ $diff_time -gt 5 ]
     then
       count=1 #Reset
     elif [ $first_run -eq 1 ]
     then
       exit
     fi
     first_run=0
}

###################################################################
# Method to print the message for user
#
###################################################################

retry_msg_babel_trace () {

     xcount=$(( $count%60 ))
     if [[ $count = 1 ]] || [[ $xcount = 0 && $count < 1081 ]] 
     then
        attempt=$(($((count / 60)) + 1))
        retry=$((3 - $((count / 60))))
        if [ $count -eq 1 ]
        then
           echo "$(date -u +'[%Y-%m-%d %H:%M:%S]') BABELWRAP-INFO: Babeltrace Viewer connection lost; either session '$session_id' is destroyed or target is restarting...."
        fi
        echo "$(date -u +'[%Y-%m-%d %H:%M:%S]') BABELWRAP-INFO: Retrying for connection or Press ctrl+c to exit... Attempt:$attempt"
        echo "$babeltrace $babelparams 2>&1"
     fi

}

if [ $live -eq 1 ]
then
   #Trying to reconnect for 1 sec; print retry message every 1 min.
   while [ $count -lt 1080 ]
   do

     start_time=$(perl -e 'print int(time)')
     $babeltrace "$@" 2>&1
     rc=$?
     if [[ $rc != 0 ]] ; then
        echo "Failed to run $babeltrace $@ 2>&1, error code: $rc. Retrying in 5 seconds..."
        sleep 5
        $babeltrace "$@" 2>&1
        rc=$?
        if [[ $rc != 0 ]] ; then
	        echo "Failed to run $babeltrace $@ 2>&1, error code: $rc. Exiting babelwrap2"
	        exit $rc #exit for none-zero return code
	fi
     fi
     cmd_exec_time
     retry_msg_babel_trace
     count=$((count + 10))
     sleep 10

   done

else
   $babeltrace "$@" 2>&1
fi


