#!/bin/bash
export MY_START_TS="$1"
export MY_END_TS="$2"
export MY_TEST_FILE="$3"
export MY_NUMBER="$4"
SOCKET="$MASTER_MYSOCK"
export MY_OUT_FILE="mysqltest_prt.$MY_NUMBER"
export MY_ERR_FILE="mysqltest_err.$MY_NUMBER"
export MY_RUN_FILE="var/tmp/run"
export PROT="run_mysqltest_prt.$MY_NUMBER"
rm -f $PROT

if [ "$MTR_BINDIR" = '' ]
then
   MTR_BINDIR='..'
fi

if [ ! -e $MY_RUN_FILE ]
then
    echo "The file ->$MY_RUN_FILE<- does not exist. Giving up" >> $PROT
    exit 4
fi

if [ ! -f $MY_TEST_FILE ]
then
   echo 'ERROR: MY_CURRENT_TS = $MY_CURRENT_TS > MY_END_TS = $MY_END_TS without any mysqltest run.' >> $PROT
   echo 'Abort' >> $PROT
   exit 4
fi

run_mysqltest()
{
   MY_CURRENT_TS=`date +%s`
   echo "MY_CURRENT_TS : $MY_CURRENT_TS , MY_START_TS : $MY_START_TS , MY_END_TS : $MY_END_TS"
   echo "MY_NUMBER : $MY_NUMBER , MY_TEST_FILE : $MY_TEST_FILE"
   echo "Begin of content of $MY_TEST_FILE ----"
   cat $MY_TEST_FILE
   echo "End   of content of $MY_TEST_FILE ----"
   if [ $MY_CURRENT_TS -gt $MY_END_TS ]
   then
      echo 'ERROR: MY_CURRENT_TS = $MY_CURRENT_TS > MY_END_TS = $MY_END_TS without any mysqltest run.'
      echo 'Abort'
   else
      while [ $MY_CURRENT_TS -lt $MY_START_TS ]
      do
         sleep 0.1
         MY_CURRENT_TS=`date +%s`
      done

      while [ $MY_CURRENT_TS -lt $MY_END_TS ]
      do
         if [ ! -e $MY_RUN_FILE ]
         then
            echo "The file ->$MY_RUN_FILE<- does no more exist. Giving up"
            break
         fi

         echo "Start executing $MY_TEST_FILE at TS: $MY_CURRENT_TS"
         $MTR_BINDIR/bin/mysqltest --verbose --user=root --database=test --socket=$SOCKET --record -x "$MY_TEST_FILE" > "$MY_OUT_FILE" 2>"$MY_ERR_FILE"
         RC=$?
         MY_CURRENT_TS=`date +%s`
         sync
         echo "End   executing $MY_TEST_FILE at TS: $MY_CURRENT_TS and status was $RC"
         echo "Begin of       output ----"
         cat $MY_OUT_FILE
         echo "End   of       output ----"
         echo "Begin of error output ----"
         cat $MY_ERR_FILE
         echo "End   of error output ----"
         # rm -f "$MY_OUT_FILE" "$MY_ERR_FILE"
         sync
         if [ $RC -gt 0 ]
         then
            if [ ! -e $MY_RUN_FILE ]
            then
               echo "The file ->$MY_RUN_FILE<- does no more exist."
               echo "Assuming that this is the reason for the exit status > 0. Giving up"
               break
            else
               echo "Removing the file ->$MY_RUN_FILE<-. Giving up"
               rm -rf $MY_RUN_FILE
               sync
               sleep 10
               exit $RC
            fi
         fi
         sleep 1.0
         MY_CURRENT_TS=`date +%s`
      done
   fi

   echo ENDE $MY_CURRENT_TS
   sync
}

run_mysqltest >> $PROT 2>&1 &

