#! /bin/sh -
Syntax() {
	echo 1>&2 "Syntax : `basename $0` [args] worksheetfile"
	echo 1>&2 "  Optional arguments:"
	echo 1>&2 "  -h, --help                   Print this message and quit"
	echo 1>&2 "  --parameter name=value       One parameter in name=value format"
	echo 1>&2 "  --parameters 'n1=\"v1\",n2=\"v2\"'  Parameters in comma separated list of name=value pairs (the entire list must be surrounded by single quotes and each value must be in double quotes)"
	echo 1>&2 "  --pfile|parameter.file file  Name of file containing parameter values in Java properties format"
	echo 1>&2 "  --invalidate[.nodes] <nodes> Worksheet nodes to be invalidated before executing the worksheet"
	echo 1>&2 "  --runto[.nodes] <nodes>      Worksheet nodes to \"run to\" to execute the worksheet"
	echo 1>&2 "  <nodes> can be \"all\" for all nodes, \"none\" for no nodes, or comma separated list of integers specifying node numbers: \"3,5,8\". Default is \"all\"."
	echo 1>&2 "  --wsd directory              Name of the worksheet directory to use (if not specified a temporary directory will be created in the current working directory)"
	echo 1>&2 "  --logfile file               Write detailed IMiner log messages to file"
	echo 1>&2 "  --appendlog                  Append log messages to existing file (default is to overwrite)"
	echo
	echo 1>&2 "  Optional S-PLUS arguments:"
	echo 1>&2 "  --cwd directory     Change to this directory before doing anything else"
	echo 1>&2 "  --headless          Enable headless mode"
	echo 1>&2 "  --output file       Send output to file (default <basename worksheet>_out.txt)"
	echo 1>&2 "  --work directory    Use directory for working database (where=1), making it if needed"
	echo 1>&2 "  If work is not specified a new randomly named directory for the working database will be created"
	echo 1>&2 "  --newworkparent dir Directory in which to make the new randomly named working database"
	echo 1>&2 "  --background        Run S-PLUS in the background (returning immediately)"
	echo 1>&2 "  --noclean           Do not remove the temporary directories used for the IMiner worksheet and S-PLUS working database or the input file"
	echo 1>&2 "  --echo              Echo command lines to output (sets options(echo=T)) (this is the default)"
	echo 1>&2 "  --verbose           Echo verbose logging information to output (sets options(verbose=T))"
	echo 1>&2 "  --vanilla           Do not run user-defined startup scripts or functions and create temporary working database (--work is ignored)"
	echo 1>&2 "  name=value          Will be added to environment so getenv(\"name\") returns \"value\""
}
Error() {
	echo 1>&2; 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
}

cwd=.
newwork_flag="--newwork"
out_specified=no
outputfile=""
inputfile=""
noclean=""
command="Splus START --bigdata --quitonerror"
imworksheet=""
imwsd=""
imwsdtemp=""
imargs=""
imparameters=""
while [ $# -gt 0 ]
do
    case "$1" in
	-h|-help|--help) Syntax
	    exit 0
	    ;;
        -j) 
#  unnecessary, bigdata is set by default
            ;;
        -output|--output)
	    ExtraArg "$1" "$2"
	    outputfile="$2"
            shift
	    out_specified=yes
            ;;
	-cwd|--cwd)
	    ExtraArg "$1" "$2"
	    DirectoryArg "$1" "$2"
	    shift
	    cwd=$1
	    cd "$cwd" || Error "Cannot change directory to $cwd"
	    ;;
        -work*|--work*)
	    ExtraArg "$1" "$2"
            command="$command $1 $2"
	    newwork_flag=""
	    shift
            ;;
	-bigdata|--bigdata)
#  this is already set
	    ;;
	-nobigdata|--nobigdata)
#  ignore, --bigdata must be set
	    ;;
	-newwork|--newwork) 
#  this is already set
	    ;;
	-newworkparent|--newworkparent)
	    ExtraArg "$1" "$2"
	    command="$command $1 $2"
	    shift
	    ;;
	-echo|--echo) command="$command $1"
	    ;;
	-noclean|--noclean) command="$command $1"
	    noclean="yes"
	    ;;
	-background|--background) command="$command $1"
	    ;;
	-verbose|--verbose) command="$command $1"
	    ;;
	-noverbose|--noverbose) command="$command $1"
	    ;;
	-quitonerror|--quitonerror) 
#  this is already set
	    ;;
	-noquitonerror|--noquitonerror) 
#  don't allow this 
	    ;;
	-headless|--headless) command="$command $1"
	    ;;
	-vanilla|--vanilla) command="$command $1"
#         don't need to specify both vanilla and newwork
	    newwork_flag=""
	    ;;
##
## arguments to call bd.run.iminer.worksheet() in Splus
##
         -parameter|--parameter)
	    ExtraArg "$1" "$2"
 	    echo "$2" | grep '=' > /dev/null
            status=$?
            if [ "$status" = "0" ] ; then
	        imparm="`echo $2 | sed -e 's/=/=\"/' -e 's/\$/\"/'`"
	        if [ -z "$imparameters" ] ; then
	    	    imparameters="$imparm"
		else 
	    	    imparameters="$imparameters, $imparm"
		fi
	    else
		 Syntax ;
            	 Error "Unrecognized argument $1"
	    fi
	    shift
	    ;;
         -parameters|--parameters)
	    ExtraArg "$1" "$2"
	    if [ -z "$imparameters" ] ; then
	    	    imparameters="$2"
	    else
	    	    imparameters="$imparameters, $2"
	    fi
	    shift
	    ;;
	-pfile|--pfile|-parameter.file|--parameter.file)
	    ExtraArg "$1" "$2"
	    [ -n "$imargs" ] && imargs="$imargs, "
	    imargs="$imargs parameter.file=\"$2\""
	    shift
	    ;;
	-invalidate|--invalidate|-invalidate.nodes|--invalidate.nodes)
	    ExtraArg "$1" "$2"
	    [ -n "$imargs" ] && imargs="$imargs, "
	    if [ "$2" = "all" -o "$2" = "none" ] ; then
		imargs="$imargs invalidate.nodes=\"$2\""
	    else
		imargs="$imargs invalidate.nodes=c($2)"
	    fi
	    shift
	    ;;
	-runto|--runto|-runto.nodes|--runto.nodes)
	    ExtraArg "$1" "$2"
	    [ -n "$imargs" ] && imargs="$imargs, "
	    if [ "$2" = "all" -o "$2" = "none" ] ; then
		imargs="$imargs runto.nodes=\"$2\""
	    else
		imargs="$imargs runto.nodes=c($2)"
	    fi
	    shift
	    ;;
	-logfile|--logfile)
            ExtraArg "$1" "$2"
	    [ -n "$imargs" ] && imargs="$imargs, "
	    imargs="$imargs logfile=\"$2\""
            shift
            ;;
	-appendlog|--appendlog)
	    [ -n "$imargs" ] && imargs="$imargs, "
	    imargs="$imargs append.log=TRUE"
	    ;;
	-wsd|--wsd)
	    ExtraArg "$1" "$2"
	    imwsd="$2"
	    shift
	    ;;

        -*) Syntax ;
            Error "Unrecognized argument $1"
            ;;
         *) echo "$1" | grep '=' > /dev/null
            status=$?
            if [ "$status" = "0" ] ; then
	        command="$command `echo $1 | sed -e s/=/=\'/ -e s/\$/\'/`"
	    else
	        if [ "X$imworksheet" = "X" ] ; then
	        	imworksheet="$1"
		else
			 Syntax ; Error "Unrecognized argument $1"
		fi
	    fi
	    ;;
    esac
    shift
done

[ "X$imworksheet" = "X" ] && { Syntax ; Error 'Worksheet file name not specified' ; }
base=`basename $imworksheet | sed -e 's/\.[^\.\/]*$//' `

if [ -z "$imwsd" ] ; then
	imwsdtemp="$base$$.wsd"
        imwsd=$imwsdtemp
fi
# create call to bd function
imcall="stopifnot(bd.run.iminer.worksheet( \"$imworksheet\""
if [ -n "$imparameters" ] ; then
	imcall="$imcall, parameters=c($imparameters)"
fi
if [ -n "$imargs" ] ; then
	imcall="$imcall, $imargs"
fi
imcall="$imcall, wsd.dir=\"$imwsd\" ))"

[ "$out_specified" = "no" ] && outputfile="${base}_out.txt"
[ -n "$outputfile" ] && command="$command --output $outputfile"

inputfile=${base}.ssc
if [ -s $inputfile ] ; then
	echo 1>&2 "Removing existing input file: $inputfile"
	rm $inputfile || Error "Cannot remove old input file: $inputfile"
else
	touch $inputfile || Error "Cannot create file in directory $cwd, cwd must have write permission."
fi
echo $imcall >> $inputfile
command="$command $newwork_flag --input $inputfile"

[ "$S_DEBUG" = "yes" ] && { echo; echo Executing: $command; }
[ "$S_DEBUG" = "yes" ] && { echo; echo Calling: $imcall; }
eval $command
status=$?
if [ "$noclean" != "yes" ] ; then
	rm -f $inputfile
	[ -z "$imwsdtemp" ] || rm -rf $imwsdtemp
fi
if [ "$status" != "0" ] ; then
	echo 1>&2; echo 1>&2 "Error executing worksheet: $imworksheet"
	if [ -n "$outputfile" -a -s "$outputfile" ] ; then
		echo 1>&2 "See output file for error messages: ${outputfile}"
	fi
	exit 1
else
      echo 1>&2 "See output file for execution status: ${outputfile}"
fi
