#!/usr/bin/env bash

usage() {
    echo "----------------------------------------------------------------------"
    cat "$SAGE_LOCAL/bin/sage-banner" | grep -i "version" | sed "s/\| //" | sed "s/ *\|//"
    echo "----------------------------------------------------------------------"
    echo " Optional arguments:"
    echo "  -coverage <files>  -- give info about doctest coverage of files"
    echo "  -h            -- print this help message"
    echo "  -v, -version  -- print the Sage version"
    echo "  -notebook [options] -- start the Sage notebook (options are"
    echo "                   the same as to the notebook command in Sage)"
    echo "  -inotebook [options] -- start the *insecure* Sage notebook "
    echo "  -min ...      -- do not populate global namespace (must be first option)"
    echo "  -t <files|dir>-- test examples in .py, .pyx, .sage or .tex files"
    echo "        options to '-t':   --verbose, --gdb, --long, --optional,"
    echo "                  --valgrind, --memcheck, --massif, --cachegrind,"
    echo "                  --callgrind, --randorder[=seed]"
    echo "  -advanced     -- list more options"
    echo "  file.[sage|py|spyx] [options] -- run given .sage, .py or .spyx files"
    echo "  -c cmd        -- Evaluates cmd as sage code"
    exit 1
}

usage_advanced() {
    echo "----------------------------------------------------------------------"
    cat "$SAGE_LOCAL/bin/sage-banner" | grep -i "version" | sed "s/\| //" | sed "s/ *\|//"
    echo "----------------------------------------------------------------------"
    echo "  no options below    -- start interactive session, passing options to ipython"
    echo "  filename.sage -- run the given file using Sage"
    echo "  -cleaner      -- run the Sage cleaner"
    echo "  -clisp [...]  -- run Common Lisp"
    echo "  -coverage <files>  -- give info about doctest coverage of files"
    echo "  -coverageall  -- give summary info about doctest coverage of all files in the Sage library"
    echo "  -gap <..>     -- run Sage's Gap with given arguments"
    echo "  -gdb          -- run Sage under the control of gdb"
    echo "  -gdb-ipython  -- run Sage's Ipython under the control of gdb"
    echo "  -gp <..>      -- run Sage's GP (Pari) with given arguments"
    echo "  -combinat <...> -- run sage-combinat patch management script"
    echo "  -grep <string>-- grep through all the Sage library code for string"
    echo "  -grepdoc <string>-- grep through all the Sage documentation for string"
    echo "  -h, -?        -- print help message"
    echo "  -ipython <...> -- run Sage's Ipython using the default environment (not Sage), passing additional options to Ipython"
    echo "  -kash <..>    -- run Sage's Kash with given arguments"
    #echo "  -ldist VER    -- build a library Sage distribution (for install into existing Python)"
    echo "  -lisp [...]   -- run Lisp interpreter included with Sage"
    echo "  -maxima <..>  -- run Sage's Maxima with given arguments"
    echo "  -M2 <..>      -- run Sage's Macaulay2 with given arguments"
    echo "  -merge        -- run Sage's automatic merge and test script"
    echo "  -min ...      -- do not populate global namespace (must be first option)"
    echo "  -mwrank <..>  -- run Sage's mwrank with given arguments"
    echo "  -np           -- run with no output prompts (useful for making doctests)"
    echo "  -preparse <file.sage> -- produce corresponding file.sage.py "
    echo "  -python       -- run the python interpreter"
    echo "  -q            -- quiet; start with no banner"
    echo "  -root         -- print the Sage root directory"
    echo "  -scons <..>   -- run Sage's scons"
    echo "  -sh           -- run \$SHELL ($SHELL) with Sage environment variables set"
    echo "  -singular <..>-- run Sage's singular with given arguments"
    echo "  -startuptime  -- display how long each component of sage takes to startup"
    echo "  -twistd <..>  -- run Twisted server"
    echo "  -t [-verbose] [-long] [-optional] [-only-optional=list,of,tags] <files|dir>"
    echo "                -- test examples in .py, .pyx, .sage or .tex files"
    echo "                      -long     -- include lines with the phrase 'long time'"
    echo "                      -verbose  -- print debuging output during the test"
    echo "                      -optional -- also test all #optional examples"
    echo "                      -only-optional -- only run doctests with #optional <nonempty subset of tags>"
    echo "                      -rand[=seed] -- randomize order of tests"
    echo "  -testall      -- test all source, docs, and examples in your Sage distro."
    echo "  -gthread, -qthread, -q4thread, -wthread, -pylab"
    echo "                -- pass the option through to ipython"
    echo "  -valgrind     -- this is an alias for -memcheck"
    echo "  -memcheck     -- run Sage under the control of valgrind using the memcheck tool."
    echo "                   The log files can be found in $HOME/.sage/ Those are named "
    echo "                   sage-memcheck.PID."
    echo "  -massif       -- run Sage under the control of valgrind using the massif tool."
    echo "                   The log files can be found in $HOME/.sage/ Those are named "
    echo "                   sage-massif.PID."
    echo "  -cachegrind   -- run Sage under the control of valgrind using the cachegrind tool."
    echo "                   The log files can be found in $HOME/.sage/ Those are named "
    echo "                   sage-cachegrind.PID."
    echo "  -callgrind    -- run Sage under the control of valgrind using the callgrind tool."
    echo "                   The log files can be found in $HOME/.sage/ Those are named "
    echo "                   sage-callgrind.PID."
    echo ""
    echo "You can also use -- before a long option, e.g., 'sage --optional'."
    echo ""
    exit 1
}

# SAGE startup script passes some funny options, which are
# best ignored.
if [ $# -eq 3 ]; then
   if [ $1 = '-i' -a $2 = '-colors' ]; then
       shift
       shift
       shift
   fi
fi

if [ $# -gt 0 ]; then
  if [ $1 = '-h' -o $1 = '-?' -o $1 = '-help' -o $1 = '--help' ]; then
     usage
  fi
  if [ $1 = "-advanced" -o $1 = "--advanced" ]; then
     usage_advanced
  fi
fi


LOGFILE="$DOT_SAGE/sage.log"
LOGOPT=""

sage_setup() {
    # Display the startup banner
    if [ "$SAGE_BANNER" != "no" ]; then
        cat "$SAGE_LOCAL/bin/sage-banner"
    fi
 
    cd "$SAGE_ROOT/local/bin"
    IPYTHONDIR="$DOT_SAGE/ipython" && export IPYTHONDIR
    IPYTHONRC="ipythonrc" && export IPYTHONRC
    if [ ! -d "$IPYTHONDIR" ]; then
        mkdir -p "$DOT_SAGE"
        cp -r "$SAGE_ROOT/ipython" "$DOT_SAGE/"
    fi
    sage-cleaner &
}


# Below the command
# _=sage.misc.interpreter.do_prefilter_paste('',False)

# It is very important in the following assignments
# that there is no whitespace after the backslashes.

########################################################
# Regarding printing the branch below:
#   We print a message with the library branch that
#   Sage is currently being run from. If they are using
#   main branch, we print nothing, otherwise users get
#   very confused about what branch they are using. 
########################################################



if [ $# -gt 0 ]; then
    if [ $1 = "-np" ]; then
       LOGOPT="-prompt_out=\\r $LOGOPT"
       shift
    fi
fi

sage() {
    sage_setup
    sage-ipython "$@" -i
}

if [ $# -eq 0 ]; then  
    sage
    exit $?
fi 

if [ $1 = '-cleaner' ]; then
    sage-cleaner
    exit $?
fi

if [ $1 = '-min' -o $1 = '--min' ]; then
    SAGE_IMPORTALL="no"
    export SAGE_IMPORTALL
    shift
    sage-sage "$@"
    exit $?
fi

#####################################################################
# Report information about the Sage environment
#####################################################################

if [ $1 = '-v' -o $1 = '-version' -o $1 = '--version' ]; then
    cat "$SAGE_LOCAL/bin/sage-banner" | grep -i "version" | sed "s/\| //" | sed "s/ *\|//"
    exit $?
fi

if [ $1 = '-root'  -o $1 = '--root' ]; then
    echo "$SAGE_ROOT"
    exit 0
fi

#####################################################################
# Run Sage's versions of the standard Algebra/Geometry etc. software
#####################################################################

if [ $1 = '-axiom' -o $1 = '--axiom' ]; then
    cd "$CUR"
    shift
   axiom "$@"
    exit $?
fi

if [ $1 = '-combinat' -o $1 = '--combinat' ]; then
    cd "$CUR"
    shift
    sage-combinat "$@"
    exit $?
fi

if [ $1 = '-gap' -o $1 = '--gap' ]; then
    cd "$CUR"
    shift
    gap "$@"
    exit $?
fi

if [ $1 = '-gp'  -o $1 = '--gp' ]; then
    cd "$CUR"
    shift
    gp "$@"
    exit $?
fi

if [ $1 = '-singular'  -o $1 = '--singular' ]; then
    cd "$CUR"
    shift
    singular "$@"
    exit $?
fi

if [ $1 = '-twistd'  -o $1 = '--twistd' ]; then
    cd "$CUR"
    shift
    twistd "$@"
    exit $?
fi

if [ $1 = '-clisp'  -o $1 = '--clisp' ]; then
    cd "$CUR"
    shift
    clisp "$@"
    exit $?
fi

if [ $1 = '-lisp'  -o $1 = '--lisp' ]; then
    cd "$CUR"
    shift
    lisp "$@"
    exit $?
fi

if [ $1 = '-kash'  -o $1 = '--kash' ]; then
    cd "$CUR"
    shift
    kash "$@"
    exit $?
fi

if [ $1 = '-fixdoctests' -o $1 = '--fixdoctests' ]; then
    cd "$CUR"
    shift
    sage-fixdoctests "$@"
    exit $?
fi

if [ $1 = '-maxima'  -o $1 = '--maxima' ]; then
    cd "$CUR"
    shift
    maxima "$@"
    exit $?
fi

if [ $1 = '-mwrank'  -o $1 = '--mwrank' ]; then
    cd "$CUR"
    shift
    mwrank "$@"
    exit $?
fi

if [ $1 = '-M2'  -o $1 = '--M2' ]; then
    cd "$CUR"
    shift
    # It is critical to use an exact path for any optional packages.
    "$SAGE_LOCAL"/bin/M2 "$@"
    exit $?
fi

if [ $1 = '-scons'  -o $1 = '--scons' ]; then
    cd "$CUR"
    shift
    scons "$@"
    exit $?
fi

if [ $1 = '-python'  -o $1 = '--python' ]; then
    cd "$CUR"
    shift
    python "$@"
    exit $?
fi

if [ $1 = '-R'  -o $1 = '--R' ]; then
    cd "$CUR"
    shift
    R "$@"
    exit $?
fi

if [ $1 = '-ipython'  -o $1 = '--ipython' ]; then
    cd "$CUR"
    shift
    ipython "$@"
    exit $?
fi

if [ $1 = '-sh'  -o $1 = '--sh' ]; then
    # AUTHORS: 
    #   Carl Witty and William Stein: initial version
    #   Craig Citro: add options for not loading profile
    cd "$CUR"
    shift
    echo ""
    echo "Starting subshell with Sage environment variables set."
    echo "Be sure to exit when you are done and do not do anything"
    echo "with other copies of Sage!"
    echo ""
    SHELL_NAME=`basename $SHELL`
    if [ $# -eq 0 ]; then
	SHELL_OPTS=""
    else
        shift
        echo "Bypassing shell configuration files ..."
        echo
        # We must start a new shell with no .profile or .bashrc files
        # processed, so that we know our path is correct
	PS1="sage$ "
	export PS1
	case $SHELL_NAME in
	    bash)
		SHELL_OPTS=" --norc"
		;;
	    csh)
		SHELL_OPTS=" -f"
		;;
	    ksh)
		SHELL_OPTS=" -p"
		;;
	    sh)
		SHELL_OPTS=" --norc"
		;;
	    tcsh)
		SHELL_OPTS=" -f"
		;;
	    zsh)
		SHELL_OPTS=" -f -d"
		;;
	    *)
		echo "Unknown shell: $SHELL!"
		echo "Exiting Sage."
		exit 1
	esac
    fi
    $SHELL_NAME $SHELL_OPTS "$@"
	
    echo Exited Sage subshell.
    exit $?
fi

if [ $1 = '-gdb-ipython'  -o $1 = '--gdb-ipython' ]; then
    cd "$CUR"
    shift
    sage-gdb-ipython "$@"
    exit $?
fi

#####################################################################
# Test coverage of a module?
#####################################################################

if [ $1 = "-coverage" -o $1 = "--coverage" ]; then
   cd "$CUR"
   shift
   sage-coverage "$@"
   exit $?
fi

if [ $1 = "-coverageall" -o $1 = "--coverageall" ]; then
   cd "$CUR"
   shift
   sage-coverageall "$@"
   exit $?
fi

#####################################################################
# Run Distributed Sage
#####################################################################

if [ $1 = "-server" -o $1 = "--server" ]; then
   shift
   sage-dsage-server "$@"
   exit $?
fi

if [ $1 = "-worker" -o $1 = "--worker" ]; then
   shift
   sage-dsage-worker "$@"
   exit $?
fi

if [ $1 = "-dsage" -o $1 = "--dsage" ]; then
   shift
   sage-dsage-server & sage-dsage-worker
   exit $?
fi

#####################################################################
# Run Sage's versions of the standard Algebra/Geometry etc. software
#####################################################################

if [ $1 = "-notebook"  -o $1 = '--notebook' ]; then
   cd "$CUR"
   shift
   sage-cleaner &
   sage-notebook "$@"
   exit $?
fi

if [ $1 = "-inotebook"  -o $1 = '--inotebook' ]; then
   cd "$CUR"
   shift
   sage-cleaner &
   sage-notebook-insecure "$@"
   exit $?
fi

if [ $1 = "-wiki"  -o $1 = '--wiki' ]; then
   cd "$CUR"
   shift
   sage-wiki "$@"
   exit $?
fi

if [ $1 = "-log" -o $1 = "--log" ]; then
   sage-log
   exit 0
fi

if [ $1 = '-grep' -o $1 = "--grep" ]; then
   sage_setup
   shift
   sage-grep "$@"
   exit 0
fi 

if [ $1 = '-grepdoc' -o $1 = "--grepdoc" ]; then
   sage_setup
   shift
   sage-grepdoc "$@"
   exit 0
fi 

if [ $1 = '-q' ]; then
   SAGE_BANNER="no"
   sage_setup
   shift
   sage "$@"
   exit $?
fi 

if [ $1 = '-t' ]; then
   if ! [  -f  "$DOT_SAGE"/init.sage ]; then
      echo "init.sage does not exist ... creating"
      touch "$DOT_SAGE"/init.sage
   fi
   cd "$CUR"
   shift 
   sage-test "$@"
   exit $?
fi

if [ $1 = '-tp' ]; then
   if ! [  -f  "$DOT_SAGE"/init.sage ]; then
      echo "init.sage does not exist ... creating"
      touch "$DOT_SAGE"/init.sage
   fi
   cd "$CUR"
   shift
   sage-ptest "$@"
   exit $?
fi

if [ $1 = '-testall' -o $1 = "--testall" ]; then
   shift
   sage-maketest "$@"
   exit $?
fi

if [ $1 = '-c' ]; then
   cd "$CUR"
   shift 
   SAGE_BANNER="no"
   sage_setup
   sage-eval "$@"
   exit $?
fi

if [ $1 = '-gdb' -o $1 = "--gdb" ]; then
    sage_setup
    sage-gdb
    exit $?
fi

if [ $1 = '-preparse' -o $1 = "--preparse" ]; then
    shift
    cd "$SAGE_LOCAL/bin/"
    sage-preparse "$CUR" "$@"
    exit $?
fi

if [ $1 = "-cython" -o $1 = '--cython' -o $1 = '-pyrex' -o $1 = "--pyrex" ]; then
    shift
    cd "$CUR"
    sage-cython "$@"
    exit $?
fi

if [ $1 = '-valgrind' -o $1 = "--valgrind" -o $1 = '-memcheck' -o $1 = "--memcheck" ]; then
    sage_setup
    sage-valgrind
    exit $?
fi

if [ $1 = '-massif' -o $1 = "--massif" ]; then
    sage_setup
    sage-massif
    exit $?
fi

if [ $1 = '-cachegrind' -o $1 = "--cachegrind" ]; then
    sage_setup
    sage-cachegrind
    exit $?
fi

if [ $1 = '-callgrind' -o $1 = "--callgrind" ]; then
    sage_setup
    sage-callgrind
    exit $?
fi

if [ $1 = '-startuptime' -o $1 = '--startuptime' ]; then
    python "$SAGE_LOCAL"/bin/sage-startuptime.py
    exit $?
fi
if [ $1 = '-gthread' -o $1 = '-qthread' -o $1 = '-q4thread' -o $1 = '-wthread' -o $1 = '-pylab' ]; then
    sage $1
    exit $?
fi

if [ $# -ge 1 ]; then
   T=`echo "$1" | sed -e "s/.*\.//"`
   cd "$SAGE_LOCAL/bin/"
   sage-run "$CUR" "$@"
   exit $?
fi

