#! /bin/bash
#
# PURPOSE: Run the QNX simulator from Matlab. This is the companion script to
#          qnx.m The mission file name is the first argument, followed by a
#          list of supported missions.
#
# AUTHORS: 1. Rob McEwen, 2015/April/14, initial.
# 
#missionList="SimWCakeSimple.cfg Flat4c.cfg PortOALow2.cfg"
#echo "QNX bash script executing."
#cd $AUV/../offboard
#pwd
#missionList=`cat missionList.txt`
#
# if [ $# -ne 1 ]
# then
#     echo " "
#     echo " Please provide a mission file including the .cfg suffix."
#     echo " Pre-setup missions are:"
#     for mission in $missionList
#     do
# 	echo "    $mission"
#     done
#     echo " "
#     exit -1
# fi
#missionList=$*;
missionList="${@:2}"
echo $missionList
recognized=false
useTrn=""
save()
{
    cp -p simulator.cfg simulatorSave.cfg
    cp -p vehicle.cfg   vehicleSave.cfg
    cp -p workSite.cfg  workSiteSave.cfg
    if [ -a terrainAid.cfg ]
    then
	cp -p terrainAid.cfg terrainAidSave.cfg
    fi
}
restore()
{
    cp -p simulatorSave.cfg simulator.cfg
    cp -p vehicleSave.cfg   vehicle.cfg
    cp -p workSiteSave.cfg  workSite.cfg
    if [ -a terrainAidSave.cfg ]
    then
	cp -p terrainAidSave.cfg terrainAid.cfg
	rm terrainAidSave.cfg
    fi
}
#
cd $AUV/missions
pwd
#
if [ -a "$1" ] 
then

    for mission in $missionList
    do
	if [ "$1" = "$mission" ]
	then
	    echo "Setting up $1"
	    recognized=true
	    cd $AUV_CONFIG_DIR
	    save
	fi
    done

    pwd

    if [ "$recognized" = true ]
    then
	if [ -a simulator$1 ]
	then
	    echo "Copying simulator$1."
	    cp -pR simulator$1 simulator.cfg
	else
	    echo "Can't find simulator$1.  Exiting."
	    restore
	    exit -1
	fi
	if [ -a vehicle$1 ]
	then
	    echo "Copying vehicle$1."
	    cp -pR vehicle$1 vehicle.cfg
	else
	    echo "Can't find vehicle$1.  Exiting."
	    restore
	    exit -1
	fi
	if [ -a workSite$1 ]
	then
	    echo "Copying workSite$1."
	    cp -pR workSite$1 workSite.cfg
	else
	    echo "Can't find workSite$1.  Exiting."
	    restore
	    exit -1
	fi
	if [ -a terrainAid$1 ]
	then
	    echo "Copying terrainAid$1."
	    cp -pR terrainAid$1 terrainAid.cfg
	    #useTrn="-trn"
	fi
    fi
    sleep 5
    echo " "
    echo "Starting the simulation:"
    echo " "
    cd $AUV/bin
    #../../offboard memscript &
    #supervisor -fastsim -plan $1 > /dev/null >& /dev/null
    supervisor -fastsim $useTrn -plan $1 
    #kill %1
    cd $AUV_CONFIG_DIR
    if [ "$recognized" = true ]
    then
	restore
	echo "Restoring .cfg files."
	echo "TRN argument = $useTrn."
    fi
    ls -l $AUV_LOG_DIR/latest
else
    echo "Can't find $1"
    exit -1
fi
