#!/bin/sh

# 
#  Copyright (C) 2008-2009  Smithsonian Astrophysical Observatory
#
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


#### cxcwrapper
####
#### This script is intended to run an application in the cxcds while
#### taking the following into consideration
####    * verification that the cxcds environment is at least minimally
####      configured before attempting to run any tasks
####    * if an explicit task path is provided use it, otherwise use
####      the ASCDS_INSTALL/bin version of the task
####    * if the -t option is specified, send an xpa toolstatus message
####      back to the application initiating the request (specified on
####      the command line-  cxcwrapper -t prism dmlist...)
####

#### routine to print usage
Instruct()
{
   echo "-- CXC wrapper script"
   echo  "Usage:  cxcwrapper [-ehmstx]"
   echo "   -e      =  echo stderr/out and send xpa toolstatus msg to dest" 
   echo "              cxcwrapper -e <dest> <command> <command args>"
   echo "   -h      =  This help message"
   echo "   -m      =  send <type> msg to <dest> w/ <key> upon completion"
   echo "              cxcwrapper -m <dest> <type> <key> <command> <command args>"
   echo "   -s      =  run the tool suppressing sterr/stdout"
   echo "   -t      =  send xpa toolstatus msg to tool agent process"
   echo "              cxcwrapper -t <dest> <command> <command args>"
   echo "   -x      =  run application w/in an xterm (or compatible) window,"
   echo "              as per the terminal settings within ciao.par.  NB: this"
   echo "              should ONLY be used for interactive applications."
   exit 1
}



#### routine to check environment/perform initialization
Initialize()
{
   ####  ensure CXC environment is configured 
   if [ "$ASCDS_INSTALL" = "" ] ; then
      echo "ERROR: ASCDS_INSTALL is undefined, please configure CIAO!"
      sleep 3
      exit
   fi

   LD_LIBRARY_PATH=$ASCDS_INSTALL/lib:$LD_LIBRARY_PATH
   export LD_LIBRARY_PATH

   #### default to not send toolstatus xpa msg
   sendToolStatus=0

   #### default to not suppress stderr/stdout
   suppress=0

   #### set name of temp file to include current process id
   pid=$$
   tempfile="/tmp/.cxc_temp_"$pid
}

LaunchTerm()
{
   # Mechanism for launching interactive applications in their own terminal
   # window.  By default CIAO uses xterm, but the 'term' parameter in
   # ciao.par may be set to any xterm-compatible terminal.  When the window
   # is launched it looks for X resources as if it were named "ciaoterm," 
   # (see $HOME/.CXCdefaults file for initial settings).  The ciao.par file
   # also contains a 'termopts' parameter, which is a means of specifying 
   # additional startup options (e.g., title) just as at the commandline.

   Term=`pget ciao term 2> /dev/null`
   if [ $? != 0 ] ; then
      Term="xterm"
   fi 
   Options=`pget ciao termopts 2> /dev/null`
   if [ $? != 0 ] ; then
      Options=""
   fi 
   if [ "$Term" = "" ] ; then
      Term="xterm"
   fi 
   # handle xterms which reset LD_LIBRARY_PATH 
   if [ -x $ASCDS_INSTALL/bin/ciaorun ] ; then
      ASCDS_RUN_CONFIG="": $Term -name ciaoterm $Options -e ciaorun $*
   else
      $Term -name ciaoterm $Options -e $*
   fi
}

#### Begin by performing initialization 
if [ "$ASCDS_DEBUG" != "" ] ; then
      echo "`basename $0`: args are $@"
      set -x
fi
Initialize

#### handle command line options 

set -- `getopt ehmstx $* `
if [ $? != 0 ] ; then
   Instruct
fi

while [ $1 != -- ] ; do
  case $1 in

        -e)     # echo stderr/stdout and set toolstatus to dest 
                sendToolStatus=3
		;;

        -m)     # send a message <access point> to <dest>
                sendToolStatus=2
                ;;

        -s)     # suppress stderr/stdout
                suppress=1
                ;; 

        -t)     # send a tool status message to dest
                sendToolStatus=1
		;;

        -x)     # Run in xterm-compatible window
                shift; 
        	opts="$@"
                opts=`echo $opts | sed 's/--//'`
		LaunchTerm $opts
		exit $?
                ;;

        *)      Instruct
                ;;

  esac
  shift
done
shift

#### process message 
if [ $sendToolStatus != 0 ] ; then

   # send toolstatus msg to toolagent after tool completes 
   if [ $# -gt 1 ]   #### ensure there are enough args
   then
      app=$1
      shift 
      if [ $sendToolStatus = 2 ]
      then 
         if [ $# -gt 2 ]   #### ensure there are enough args
         then
            acspnt=$1
            shift
            key=$1
            shift
         else
            echo "ERROR: Insufficient number of arguments for -m option"
            exit 1; 
         fi
      fi
      if [ "$ASCDS_DEBUG" != "" ] || [ $sendToolStatus = 3 ]; then
         #### write command to tmp file & source it- to handle quotes
         rm -rf $tempfile
         echo $* > $tempfile
         chmod 766 $tempfile
         $tempfile
         status=$?
         rm -rf $tempfile
      else
         #### write command to tmp file & source it- to handle quotes
         rm -rf $tempfile
         echo $* > $tempfile
         chmod 766 $tempfile
         $tempfile
         status=$?
         rm -rf $tempfile
      fi
      if [ $sendToolStatus = 2 ] ; then
         xpaset -p $app $acspnt $key $1 $status 2> /dev/null 1>&2
      else
         xpaset -p $app toolstatus $1 $status 2> /dev/null 1>&2
      fi
   else
      if [ $sendToolStatus = 2 ] ; then
         echo "ERROR: Insufficient number of arguments for -m option"
      else
         echo "ERROR: Insufficient number of arguments for -t option"
      fi
      exit 1; 
   fi

elif [ "`basename $1`" = "$1" ] ; then

   #### write command to tmp file & source it- to handle quotes
   rm -rf $tempfile
   # If not an explicitly-pathed executable, look for it w/in CXCDS bin

   echo $ASCDS_INSTALL/bin/$@ > $tempfile
   chmod 766 $tempfile
   if [ $suppress = 1 ] ; then
      $tempfile 2> /dev/null 1>&2
   else
      $tempfile
   fi 
   status=$?
   rm -rf $tempfile

else
   if [ $suppress = 1 ] ; then
      # execute tool suppressing stderr/stdout
      $@ 2> /dev/null 1>&2
   else
      # simply execute tool
      $@
   fi
fi

exit 0
