#! /bin/bash
FILENAME=$1
if [ ! -e $FILENAME ]; then
    echo Mission file $FILENAME not found
    exit 1
fi
if [ ! -s $FILENAME ]; then
    echo Mission file $FILENAME is zero length
    exit 1
fi


sed 's/\#define/\%define/' $FILENAME | sed 's/\#/\/\//' | sed 's/\%define/\#define/' | cpp -C -P -x c++ | sed 's/\/\//\#/' > $FILENAME.pp
if [ ! -e $FILENAME.pp ]; then
    echo Mission file $FILENAME.pp not found or zero length
    exit 1
fi

cat $FILENAME.pp;
gzip -f $FILENAME.pp;
echo "AUV_HOST is " $AUV_HOST

AUV_PLAN_DIR=$(rsh -l dorado1 $AUV_HOST ">&2 echo \$AUV_PLAN_DIR" 2>&1 1>/dev/null)
echo "AUV_PLAN_DIR on host" $AUV_HOST "is " $AUV_PLAN_DIR

ncftpput -u dorado1 -p dorado1 $AUV_HOST $AUV_PLAN_DIR $FILENAME.pp.gz
if [ $? != 0 ]; then
    echo FTP to $AUV_HOST failed!
    exit 1;
else
    echo FTP of mission $FILENAME.pp.gz successful\!
fi

echo Running gunzip of $FILENAME.pp.gz
STATUS=$(rsh -l dorado1 $AUV_HOST "cd \$AUV_PLAN_DIR; gunzip -f $FILENAME.pp.gz 2> /dev/null; >&2 echo \$?" 2>&1 1>/dev/null)
if [ $STATUS != 0 ]; then
    echo unzip of $FILENAME.pp.gz failed
    exit 1;
else
    echo Gunzip of mission $FILENAME.pp.gz successful\!
fi

# echo Running Checkplan of $FILENAME.pp
# rsh -l dorado1 $AUV_HOST "cd \$AUV/bin; workSite >> /dev/null 2>> /dev/null &" 2>&1 1>/dev/null
# STATUS=$(rsh -l dorado1 $AUV_HOST "cd \$AUV_PLAN_DIR; checkplan $FILENAME.pp 2> /tmp/checkplan.out; >&2 echo \$?" 2>&1 1>/dev/null)
# rsh -l dorado1 $AUV_HOST "slay workSite"  2>&1 1>/dev/null
# if [ $STATUS != 0 ]; then
#     echo checkplan of $FILENAME.pp failed
#     rsh -l dorado1 $AUV_HOST cat /tmp/checkplan.out
#     exit 1;
# else
#     echo checkplan of $FILENAME.pp successful\!
# fi

echo "starting mission $FILENAME.pp";
STATUS=$(rsh -l dorado1 $AUV_HOST "cd \$AUV/bin; nohup supervisor -plan $FILENAME.pp >> /dev/null 2>> /dev/null &  >&2 echo \$?" 2>&1 1>/dev/null)
if [ $STATUS != 0 ]; then
    echo startup of $FILENAME.pp failed
    exit 1;
else
    echo Start of mission $FILENAME.pp successful \!
fi

echo All Done
exit 0

