#!/bin/bash
#==============================================================
#  Name: rfViewLogRecent.bash
#  Abs:  Display log file
#
#  Facility: LCLS-II
#
#  Auth: Sonya Hoobler, 23 May 2018
#  Rev:  dd-mmm-yyyy, First Lastname (USERNAME)
#
#
#--------------------------------------------------------------
#  Mod:
#
#--------------------------------------------------------------
#
#  Usage:
#         rfViewLogRecent.bash <path> <filter> <filename> <mode> [older]
#
#         Displays most recent log file. Assumes that the
#         directory structure is <path>/*<filter>*/<filename>.
#         ":" are replaced by "_"
#
#============================================================

function usage {
echo "
   Purpose: Display current log file (or optionally older)

   Usage:
	  rfViewLogRecent.bash <path> <filter> <filename> <mode> [older]

        path, filter, filename are used to find: <path>/*<filter>*/<filename>
          In filter, : are replaced by _

        mode = 0 to display contents as-is
               1 to display them in reverse order
                 Note that tail 'follow' mode is not used

        Optional argument:

        older = display older file, counting in reverse from 1

"
}

# Check for input arguments
NARGS=$#
if [[ $NARGS -ne 4 &&  $NARGS -ne 5 ]]
then
        echo "rfViewLogRecent.bash: 4 or 5 arguments expected, but received ${NARGS}."
	usage
        exit 0
fi

PATHARG=`echo $1 | tr : _`
FILTERARG=`echo $2 | tr : _`
FILEARG=`echo $3 | tr : _`
MODEARG=`echo $4`

if [ $NARGS -eq 5 ]
then
    NTH=`echo $5`
    echo "Display ${NTH}th newest file"
else
    NTH=1
fi


LOG=`ls -td ${PATHARG}/*${FILTERARG}*/*${FILEARG}* | head -n ${NTH} | tail -n 1`

RVAL=${PIPESTATUS[0]}
if [ $RVAL -ne 0 ]
then
    echo "rfViewLogRecent.bash: ls of log file failed:"
    echo "echo ls -td ${PATHARG}/*${FILTERARG}*/*${FILEARG}* | head -n ${NTH} | tail -n 1"
    exit 0
fi

echo "Displaying log file: $LOG"
echo ""

if [ $MODEARG -eq 0 ]
then
	tail -F -n 10000 $LOG
else
	tail -n 10000 $LOG | tac
fi
