#!/bin/bash
# 
#  Copyright (C) 2007,2012-2014,2019,2020,2023  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.
#

#

usage() 
{
   echo "-- sherpa"
   echo "  usage: sherpa [-x] [-n] [-b] [-rcfile file] [-norcfile] <file>"
   echo "     -x       launch sherpa shell in separate display terminal"
   echo "     -n       do not print banner"
   echo "     -b       batch mode"
   echo "     -rcfile  load a user specifiable preference file"
   echo "     -norcfile do not load any user specifiable preference file (overrides -rcfile)"
   echo "     <file>   Python command file to execute"
   exit 1
}

sherpa_ver_check()
{
   #Report the current version of Sherpa in the environment
   default_version="`python -c "import sherpa; print(sherpa._version.get_versions()['version'])"`"
   if [ "$?" = "0" ]; then
       echo "Sherpa ${default_version}"
   else
       echo ""
       echo "Sherpa ERROR: Failed to import Sherpa and check its version."
       echo "Verify that Sherpa is installed or resolve issues noted in traceback above."
       exit -1
   fi
}

banner()
{
   echo "-----------------------------------------------------"
   echo "Welcome to Sherpa: CXC's Modeling and Fitting Package"
   echo "-----------------------------------------------------"
   if [ "x${ASCDS_INSTALL}" != "x" ]; then
       if [ -r ${ASCDS_INSTALL}/VERSION_sherpa ]; then
	   numfields=`head -n 1 $ASCDS_INSTALL/VERSION_sherpa | awk '{print NF}'`
	   if [ $numfields = "6" ]; then
           ciao_version=`awk '{print $2}' ${ASCDS_INSTALL}/VERSION_sherpa | cut -d '.' -f 1-2`
           sherpa_version=`awk '{print $2}' ${ASCDS_INSTALL}/VERSION_sherpa | cut -d '.' -f 3` 
	       echo "CIAO ${ciao_version} Sherpa version ${sherpa_version} `awk '{print $3" "$4" "$5" "$6}' ${ASCDS_INSTALL}/VERSION_sherpa`"
	   else
               sherpa_ver_check
	   fi
       else
           sherpa_ver_check
       fi
   else
       sherpa_ver_check
   fi
   echo ""
}

printbanner="yes" xterminal= cmd= batch=
scriptFile=
argList=
rcfile=
xwin="no"

while :
do
   case "$1" in
      -x) xwin="yes";;
      -b) batch="yes"; argList="$argList -b";;
      -n) printbanner="no"; argList="$argList -n";;
      -rcfile) shift; rcfile="$1";
	  # Setting the rcfile on the command line ALWAYS overrides
	  # the SHERPARC environment variable setting (if any)
	  # verify that an rcfile was included
	  if test "x$rcfile" = "x" ; then
	     echo "Sherpa ERROR: The -rcfile switch takes one parameter. Please specify new rcfile."
             exit -1
	  else
             first_char=`expr "$rcfile" : '\(.\).*'`
             if test "$first_char" = "-"; then
                echo "Sherpa ERROR: The -rcfile switch takes one parameter. Please specify new rcfile."
                exit -1
             fi
	  fi
	  if [ ! -e "$rcfile" ]; then
	     echo "Sherpa ERROR: rcfile $rcfile does not exist."
             exit -1
	  fi
	  SHERPARC=$rcfile
	  export SHERPARC ;;
      -norcfile) NOSHERPARC=true; export NOSHERPARC;;
      -l) shift ; lang="$1";
	  if test "$lang" = "python"; then
	     # print deprecation warning, go on to next option
	     echo "Sherpa WARNING: -l is no longer an option; Sherpa now supports Python only."
	     echo ""
	  elif test "$lang" = "slang"; then
	     # print S-Lang no longer supported, exit
	     echo "Sherpa ERROR: Sherpa no longer offers a S-Lang interface."
	     exit -1
	  else
	     # If -l followed by any other string, or no
	     # string, print usage and exit.
	     echo "Sherpa ERROR: -l is no longer an option; Sherpa now supports Python only."
	     echo ""
	     usage 
	  fi
	  ;;
      --) shift; break;;
      -*) usage "bad argument $1";;
      *)
	  len=`expr "$1" : '.*'`
	  if test $len -eq 0; then
             # zero length entry- reached end of argument list processing
             break;
          else
             # support at most 1 script file
             if test "x$scriptFile" = "x"; then
                scriptFile="$1";
             else
                echo "Sherpa ERROR: Expected a single file script: $scriptFile -vs- $1"
                exit -1
             fi
          fi
          ;;
   esac
   shift
done

# now that we've processed the arg list- we can run xterm -e if specified
if test "$xwin" = "yes"; then
   xterm -e $0 $argList $scriptFile;
   exit $?
fi

# setup the users home directory with the Sherpa config files
ciao_app_setup.sh sherpa .sherpa.rc $batch

cmd=""

# if we have an additional argument treat it as a file for exec
if test "x$scriptFile" != "x"; then
    if [ ! -r "$scriptFile" ]; then
        echo "Sherpa ERROR: script file $scriptFile either does not exist or cannot be read"
        exit -1
    fi
    cmd="${cmd}exec(compile(open('$scriptFile', 'rb').read(), '$scriptFile', 'exec'));"
fi

# make sure we use the CIAO version of python
CIAO_PYTHON=${CIAO_APP_PYTHON}
CIAO_IPYTHON=${CIAO_APP_IPYTHON}
export CIAO_PYTHON
export CIAO_IPYTHON


if test "$batch" = "yes"; then
   if test "x$cmd" = "x"; then
      cmd="quit()"
   fi 
   ipython --profile sherpa -c "${cmd}"
else
   if test "$printbanner" = "yes"; then
      banner
   fi
   # python shell options should follow a -- w/ any sherpa command file last 
   if test "x$cmd" = "x"; then
      ipython --profile sherpa
   else
      ipython --profile sherpa -i -c "${cmd}"
   fi
fi
