#!/bin/bash

# This script can be called from anywhere, provided the user has
# systemsim in their PATH. If they do not, it should still run
# the old way, but only from a subdirectory under 'run'.

TRYPATH=$(/usr/bin/which systemsim 2>/dev/null)

# OS/X returns "no systemsim ..." as stdout, not stderr.  Get rid of it
TRYPATH=$(echo $TRYPATH | sed "s/^no systemsim.*$//")

if [ "$TRYPATH" ]; then
   TRYPATH=$(dirname $TRYPATH)/..
fi

SYSTEMSIM_TOP=
for TRYTOP in 	../../.. $TRYPATH;
do
   TRYTOP=$(cd $TRYTOP; pwd)
   if [ -x $TRYTOP/bin/systemsim ]; then
      SYSTEMSIM_TOP=$TRYTOP
      break
   fi
done

if [ "$SYSTEMSIM_TOP" ]; then
   export SYSTEMSIM_TOP
   if [ "$1" == "-secure" ]; then
       shift
       MACHOPT=-cellsecure
   else
       MACHOPT=-cell
   fi
   exec $SYSTEMSIM_TOP/bin/systemsim $MACHOPT $*
fi
