#!/bin/bash -ex

# To allow running out of tree check to see if the first argument is a directory.
# If so, assume that it is the test root directory and setup based around that.
# Otherwise run from the location of this script.
if [ "$#" > 1 ] && [ -d $1 ]; then
    pushd $1
    TROOT=`pwd`
    popd
    shift
    BUILD_ROOT=`pwd`
else
    TROOT=$(cd $(dirname $0) && pwd)
    BUILD_ROOT=$TROOT
fi
RTCDS=$TROOT/../support/bin/rtcds.in
RTCDS="bash -e $RTCDS"
HOSTNAME=$(hostname)
BIN=$TROOT/../support/bin

export RTS_ENV=$TROOT/env
# source "$RTS_ENV" #2>/dev/null || true
# export IFO
# export SITE
# export RTS_USER

export RTS_VERSION=?.?.?
export RCG_SRC=$TROOT/../
export RCG_DIR=$RCG_SRC
export RCG_BUILDD=$BUILD_ROOT/build
export RCG_TARGET=$BUILD_ROOT/install_target
export RCG_LIB_PATH=$BUILD_ROOT/lib

mkdir -p $RCG_LIB_PATH
sed "s|@HOSTNAME@|$HOSTNAME|" <$TROOT/x1iop.mdl >$RCG_LIB_PATH/x1iop.mdl
sed "s|@HOSTNAME@|$HOSTNAME|" <$TROOT/x1tst.mdl >$RCG_LIB_PATH/x1tst.mdl
sed "s|@HOSTNAME@|$HOSTNAME|" <$TROOT/x1iopvirt.mdl >$RCG_LIB_PATH/x1iopvirt.mdl
cp $RCG_SRC/src/include/*.h $RCG_LIB_PATH/

# Here we try  and detect if this is our first build
FIRST_BUILD=0
if [ ! -d $RCG_TARGET ];
then
FIRST_BUILD=1
mkdir -m755 -p $RCG_TARGET
fi

case $1 in
    'build')
        rm -rf $RCG_BUILDD
        $RTCDS build x1iop
        if [ $FIRST_BUILD -eq 1 ]; then
        echo "Performing test failure build of the model, so the IPCx table is populated" 
        $RTCDS build x1tst --user-space --no-kernel-space &> /dev/null || true 
        fi
        $RTCDS build x1tst --user-space --no-kernel-space
        $RTCDS build x1iopvirt --user-space --no-kernel-space
        ;;
    'install')
    	if [ -e /opt/rtcds/ ] ; then
	  $RTCDS install x1iopvirt
	  $RTCDS install x1tst
	else
	  echo "/opt/rtcds does not exist"
	  exit 1
	fi
        ;;
    'startstop')

	$BIN/rts_epics_exec x1iopvirt &
	sleep 5
	$RCG_BUILDD/models/x1iopvirt/target/bin/x1iopvirt & #& caput X1:FEC-17_BURT_RESTORE 1
	sleep 10
	$BIN/rts_epics_exec x1tst &
	sleep 5
	$RCG_BUILDD/models/x1tst/target/bin/x1tst &
	sleep 10
	pkill -9 x1tst
	sleep 1
	pkill -9 x1iopvirt
#	  $RTCDS start x1iopvirt
#	  $RTCDS start x1tst
#	  $RTCDS stop x1iopvirt
#	  $RTCDS stop x1tst

	;;
    'clean')
        rm -rf $RCG_TARGET $RCG_BUILDD $RCG_LIB_PATH
    ;;
    *)
	$RTCDS $@
	;;
esac
