#!/bin/bash
#< Script to monitor command execution where "watch" unavailable

# Not fully tested for all quoting eventualities.... your milage will vary

AWK="/usr/bin/awk"
BASENAME="/usr/bin/basename"
DATE="/bin/date"
ECHO="/bin/echo"
EGREP="/usr/bin/egrep"
PERL="/usr/bin/perl"
PRINTF="/usr/bin/printf"
SED="/usr/bin/sed"
SLEEP="/bin/sleep"
TR="/usr/bin/tr"
WHICH="/usr/bin/which"
THISPROG=$( ${BASENAME} $0 )

trap 'exit 0' 1 2 3 15

function usage {
   {
      ${ECHO} "Usage: ${THISPROG}  "
   } >&2
}

function create_divider {
   echo "==========================================================================================="
}

if [ "$#" -lt "2" ]; then
   usage
   exit 1
fi

INTERVAL=$1 && shift

${ECHO} "${INTERVAL}" | ${EGREP} '^[0-9]+$' >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
   ${ECHO} "Error: interval must be an integer value!" >&2
   exit 1
fi

# Now, we assume a lot here, i.e. that $1 will now contain the
# command that we want to execute, and that it should be in our
# $PATH
# This also only supports simple comamnds - no pipes, redirection,
# etc....
ORIGCMD="$@"
COMMAND=$( eval ${ECHO} "${ORIGCMD}" | ${TR} -d '\042\047' | ${AWK} '{print $1}')
${WHICH} "${COMMAND}" | ${EGREP} '^no ' >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
   ${ECHO} "Error: Command \"${COMMAND}\" not in \$PATH" >&2
   exit 1
fi

while [ true ]; do
   clear
   ${PRINTF} "%-60s%20s\n" "${ORIGCMD}" "$( ${DATE} )" 
   create_divider
   echo "${DIVIDER}"
   eval ${ORIGCMD}
   ${SLEEP} ${INTERVAL}
done

exit 0