#! /bin/sh -
Syntax() {
	echo 1>&2 "Arguments to `basename $0` (all optional):"
	echo 1>&2 "  --help              Print this message"
	echo 1>&2 "  -e                  Enable command line editing"
	echo 1>&2 "  -j                  Enable java"
	echo 1>&2 "  -w|--workbench      Use workbench"
	echo 1>&2 "  --headless          Enable headless mode"
	echo 1>&2 "  --cwd directory     Change to this directory before doing anything else"
	echo 1>&2 "  --input file        Read input from file"
	echo 1>&2 "  --output file       Send output to file"
	echo 1>&2 "  --logfile file      Write session log to file"
	echo 1>&2 "  --appendlog         Append to log file (default is to overwrite)"
	echo 1>&2 "  --work directory    Use directory for working database (where=1), making it if needed"
	echo 1>&2 "  --background        Run in the background (returning immediately)"
	echo 1>&2 "  --newwork           Make new, randomly named directory for working database"
	echo 1>&2 "  --noclean           Do not remove that new randomly named directory used for working database"
	echo 1>&2 "  --newworkparent dir Directory in which to make the new randomly named working database"
	echo 1>&2 "  --echo              Echo command lines to output (sets options(echo=T))"
	echo 1>&2 "  --quiet             Do not print copyright and version messages at startup"
	echo 1>&2 "  --noquiet           Print copyright and version messages at startup (the default)"
	echo 1>&2 "  --verbose           Echo verbose logging information to output (sets options(verbose=T))"
	echo 1>&2 "  --quitonerror       Terminate immediately on engine error. (Default: continue through errors)"
	echo 1>&2 "  --nobigdata         Do not load bigdata library."
	echo 1>&2 "  --bigdata           Load bigdata library, adding -j if needed."
	echo 1>&2 "  --vanilla           Do not run user-defined startup scripts or functions and set --newwork"
	echo 1>&2 "  --exec sh command   Treat the remainder of the arguments as a sh command"
	echo 1>&2 "  -g                  [DEPRECATED] Use java GUI"
	echo 1>&2 "  name=value          Will be added to environment so getenv(\"name\") returns \"value\""
        echo 1>&2 "The first hyphen in arguments of the form \"--word\" may be omitted"
}
Error() {
	echo 1>&2 "Error in `basename $0`: $1"
	exit 1
}
ExtraArg() {
    arg=$1
    case "$2" in
        "") Error "$arg needs to be followed by value" ;;
        -*) Error "$arg needs to be followed by value" ;;
    esac
}
DirectoryArg() {
    arg=$1
    case "$2" in
        "") ;;
        *) [ -d $2 ] || Error "File $2 is not a directory" ;;
    esac
}
ReadableFileArg() {
    arg=$1
    case "$2" in
        "") ;;
        *) [ -r $2 ] || Error "Cannot read file $2" ;;
    esac
}
WritableFileArg() {
    arg=$1
    file=$2
    case "$file" in
        "") ;;
# Should test writability without creating file.
# Check that $file exists and is writable or that `dirname $file` is writable directory
        *) if ( /bin/ls -d $file > /dev/null 2>&1 ) 
           then
              [ -w $file ] || Error "Cannot write into $file"
           else
              [ -w `dirname $file` ] || Error "Cannot make file `basename $file` in directory `dirname $file`"
           fi
           ;;
    esac
}
cwd=.
work=
java_flag=
cled_flag=
headless=
sh_command=
S_BACKGROUND=
SPLUS_ARGS=
S_LOGFILE_NEW=yes ; export S_LOGFILE_NEW
unset S_LOGFILE
unset S_BATCH_INPUT
unset S_BATCH_OUTPUT
unset S_QUIT_ON_ERROR
unset S_ECHO
unset S_DEBUG
unset S_RDB_MAKE
unset S_RDB_PARENT
unset S_RDB_REMOVE
unset S_VERBOSE
unset S_NO_USER_INIT_FILES
while [ $# -gt 0 ]
do
    case "$1" in
	-help|--help) Syntax
	    exit 0
	    ;;
        -g) [ "$java_flag" = "-j" ] && Error "Can supply only one java flag: -j or -g"
	    java_flag=-g
# we should remove this restriction.  We should disallow -input,
# -output, and -e when using -g.
            ;;
        -j) [ "$java_flag" = "-g" ] && Error "Can supply only one java flag: -j or -g"
	    java_flag=-j
            ;;
        -w|-workbench|--workbench) 
            java_flag=-workbench
            ;;
	-headless|--headless)
            headless=yes
            ;;
	-e) cled_flag=-e
	    ;;
	-logfile|--logfile)
            ExtraArg "$1" "$2"
            shift
            S_LOGFILE="$1" ; export S_LOGFILE
            ;;
	-nologfile|--nologfile)
	    unset S_LOGFILE
	    ;;
	-noappendlog|--noappendlog)
	    S_LOGFILE_NEW=yes ; export S_LOGFILE_NEW
	    ;;
	-appendlog|--appendlog)
	    S_LOGFILE_NEW=no ; export S_LOGFILE_NEW
	    ;;
        -input|--input)
            ExtraArg "$1" "$2"
            shift
            S_BATCH_INPUT="$1" ; export S_BATCH_INPUT
            ;;
        -output|--output)
	    ExtraArg "$1" "$2"
            shift
            S_BATCH_OUTPUT="$1" ; export S_BATCH_OUTPUT
            ;;
	-cwd|--cwd)
# Processed this before any other file processing.
# It changes meaning for other file name arguments
	    ExtraArg "$1" "$2"
	    DirectoryArg "$1" "$2"
	    shift
	    cwd=$1
	    cd "$cwd" || Error "Cannot change directory to $cwd"
	    ;;
        -work*|--work*)
	    ExtraArg "$1" "$2"
	    shift
            work=$1
            ;;
        -newwork|--newwork)
# -newwork: make a randomly named work directory
	    S_RDB_MAKE=yes
            export S_RDB_MAKE
            ;;
	-newworkparent|--newworkparent)
	    ExtraArg "$1" "$2"
	    DirectoryArg "$1" "$2"
	    shift
	    S_RDB_PARENT=$1
	    export S_RDB_PARENT
	    ;;
	-background|--background)
            S_BACKGROUND="&"
# no need to export S_BACKGROUND - used only in this script
	    ;;
	-echo|--echo)
	    S_ECHO=yes ; export S_ECHO
	    ;;
	-noclean|--noclean)
	    S_RDB_REMOVE=no ; export S_RDB_REMOVE
	    ;;
	-quiet|--quiet)
	    S_SILENT_STARTUP=yes ; export S_SILENT_STARTUP
	    ;;
	-noquiet|--noquiet)
	    unset S_SILENT_STARTUP
	    ;;
	-verbose|--verbose)
	    S_VERBOSE=yes ; export S_VERBOSE
	    ;;
	-noverbose|--noverbose)
	    S_VERBOSE=no ; export S_VERBOSE
	    ;;
	-quitonerror|--quitonerror)
	    S_QUIT_ON_ERROR=yes ; export S_QUIT_ON_ERROR
	    ;;
	-noquitonerror|--noquitonerror)
	    unset S_QUIT_ON_ERROR
	    ;;
	-nobigdata|--nobigdata)
	    unset S_LOAD_BIGDATA ;
            want_bigdata=no ;
	    ;;
	-bigdata|--bigdata)
	    S_LOAD_BIGDATA=yes ; export S_LOAD_BIGDATA
            want_bigdata=yes ;
	    ;;
	-vanilla|--vanilla)
	    S_NO_USER_INIT_FILES=yes ; export S_NO_USER_INIT_FILES
# also do what -newwork does
	    S_RDB_MAKE=yes ; export S_RDB_MAKE
	    ;;
	-exec|--exec)
	    shift
	    sh_command="$@"
	    break
	    ;;
        -*) Syntax ;
            Error "Unrecognized argument $1"
            ;;
        *)  echo "$1" | grep '=' > /dev/null
	    status=$?
	    if [ "$status" = "0" ] ; then
	        ENV_ARGS="$ENV_ARGS `echo $1 | sed -e s/=/=\'/ -e s/\$/\'/`"
	    else
	        SPLUS_ARGS="$SPLUS_ARGS $1"
	    fi
	    ;;
    esac
    shift
done
[ "$S_BATCH_INPUT" = "" ] || ReadableFileArg "-input" "$S_BATCH_INPUT"
[ "$S_BATCH_OUTPUT" = "" ] || WritableFileArg "-output" "$S_BATCH_OUTPUT"
[ "$S_LOGFILE" = "" ] || WritableFileArg "-logfile" "$S_BATCH_OUTPUT"
[ ! "$S_BATCH_INPUT" = "" -o ! "$S_BATCH_OUTPUT" = "" ] && [ "$java_flag" = "-g" ] && Error "Cannot use -input or -output with java gui (-g)"
[ "$want_bigdata" = "yes" ] && [ "$java_flag" = "" ] && java_flag=-j

if [ "$headless" = "yes" ]
then
	[ "$java_flag" != "-j" ] && Error "-headless should only be specified when -j and/or -bigdata is used"
	java_flag="-j -headless"
fi

if [ "$work" != "" ]
then
         [ -d "$work" ] || S_WORK_MADE_HERE=yes
         Splus CHAPTER -m -d "$work" || Error "Could not create chapter `pwd`/$1"
         S_WORK=$work ; export S_WORK
fi
[ X$S_BATCH_INPUT != X ] && BATCH_ARGS="< $S_BATCH_INPUT"
[ X$S_BATCH_OUTPUT != X ] && BATCH_ARGS="$BATCH_ARGS > $S_BATCH_OUTPUT 2>&1"

if [ "$sh_command" = "" ] ; then
   command="$ENV_ARGS Splus $java_flag $cled_flag $BATCH_ARGS $SPLUS_ARGS $S_BACKGROUND"
else
   command="$ENV_ARGS Splus $sh_command $BATCH_ARGS $S_BACKGROUND"
fi
eval $command
