#! /bin/sh
#
#  Shell script to ease invocation of the powerpc simulator
#
#  COPYRIGHT (c) 1989-2006.
#  On-Line Applications Research Corporation (OAR).
#
#  The license and distribution terms for this file may be
#  found in found in the file LICENSE in this distribution or at
#  http://www.rtems.com/license/LICENSE.
#
#  $Id: psim,v 1.10 2006/01/20 17:30:39 joel Exp $
#

TREE_FILE=psim_tree.${LOGNAME}
RUN=powerpc-rtems4.7-run


progname=${0##*/}        # fast basename hack for ksh, bash

USAGE=\
"usage: $progname [ -opts ] test [ test ... ]
	-v	   -- verbose
        -l limit   -- specify time limit (default is 'no limit')
"

#   log an error to stderr
prerr()
{
    echo "$*" >&2
}

fatal() {
    [ "$1" ] && prerr $*
    prerr "$USAGE"
    exit 1
}

warn() {
    [ "$1" ] && prerr $*
}

#
# process the options
#
# defaults for getopt vars
#

verbose=""
limit="0"

while getopts vl: OPT
do
    case "$OPT" in
	v)
	    verbose="yes";;
        l)
            limit="$OPTARG";;
        *)
            fatal;;
    esac
done
shiftcount=`expr $OPTIND - 1`
shift $shiftcount

args=$*

# RUN_DEBUG="-t sem_device"

#  Build this user's device tree file
echo "/#address-cells 2"                              >  ${TREE_FILE}
echo "/openprom/init/register/pvr 0xfffe0000"         >> ${TREE_FILE}
echo "/openprom/options/oea-memory-size 8388608"      >> ${TREE_FILE}
echo "/openprom/trace/semantics 1"      >> ${TREE_FILE}

# These require the semaphore and shared memory device models.
# echo "/shm@0xc0000000/reg 0xc0000000 0x10000"         >> ${TREE_FILE}
# echo "/shm@0xc0000000/key ${RTEMS_SHM_KEY}"           >> ${TREE_FILE}
# echo "/sem@0xc0010000/reg 0xc0010000 12"              >> ${TREE_FILE}
# echo "/sem@0xc0010000/key ${RTEMS_SHM_SEMAPHORE_KEY}" >> ${TREE_FILE}
# echo "/sem@0xc0010000/value -1"                       >> ${TREE_FILE}

runtest()
{
  testname=${1}
  max_run_time=${2}
  if [ ${max_run_time} -eq 0 ] ; then
    #echo run ${testname} forever
    ${RUN} -f ${TREE_FILE} ${RUN_DEBUG} ${testname}
  else
    #echo run ${testname} for maximum ${max_run_time} seconds
    ${RUN} -f ${TREE_FILE} ${RUN_DEBUG} ${testname} &
    pid=$!

    # Make sure it won't run forever...
    time_run=0
    while [ $time_run -lt $max_run_time ]
    do
      # sleep 5s at a time waiting for job to finish or timer to expire
      # if job has exited, then we exit, too.
      sleep 1
      kill -0 $pid 2> /dev/null
      running=$?
      if [ $running -eq 0 ] ; then
        time_run=$((time_run + 5))
        if [ $time_run -ge $max_run_time ]; then
	  kill -9 $pid 2> /dev/null
	  ran_too_long="yes"
          echo "${testname} killed after running ${max_run_time} seconds"
        fi
      else
        ran_too_long="no"
        break
      fi
    done
  fi
}

if [ "X${1}" = "X" ] ; then
  echo no tests to run
  exit 1
fi
runtest ${1} ${limit}
rm -f ${TREE_FILE}
exit $?

