#!/usr/local/bin/python2.6 -O

import optparse
import os
import sys
import time

if "/usr/local/lib/python2.6/site-packages" not in sys.path:
    sys.path.insert(0, "/usr/local/lib/python2.6/site-packages")
import Crux

# Create a help formatter subclass for the command line parser.
class CruxHelpFormatter(optparse.IndentedHelpFormatter):
    def format_usage(self, usage):
        return """\
crux usage:
    crux -h | --help
    crux -d <var> | --doc=<var>
    crux -V | --version
    crux [<options>] [<file>] [- [<scriptargs>]]

    Option                     | Description
    ---------------------------+------------------------------------------------
    -h, --help                 | Print usage and exit.
    -d <var>, --doc=<var>      | Print documentation for <var> and exit.
    -V, --version              | Print version information and exit.
    -b, --batch                | Run in batch mode.
    -i, --interactive          | Run in interactive mode.
    -v, --verbose              | Enable verbose output.
    -q, --quiet                | Disable verbose output.
    -t, --threaded             | Enable thread parallelism (default).
    -u, --unthreaded           | Disable thread parallelism.
    -s <int>, --seed=<int>     | Set pseudo-random number generator seed.
    -f <file>, --file=<file>   | Read input from <file>.

    Trailing argument(s) | Description
    ---------------------+------------------------------------------------------
    <file>               | Read input from <file> (same as --file=<file>).
    - [<scriptargs>]     | Provide <scriptargs> arguments to script.

crux runs interactively and verbosely by default, unless an input file is
specified, in which case crux runs in batch mode and quietly by default."""

# Process the command line.
def parse_options():
    helpformatter = CruxHelpFormatter()
    parser = optparse.OptionParser(formatter=helpformatter, add_help_option=0)
    parser.disable_interspersed_args()
    parser.add_option("-h", "--help", dest="help", action="store_true",
      default=False)
    parser.add_option("-d", "--doc", dest="doc", default=None)
    parser.add_option("-V", "--version", dest="version", action="store_true",
      default=False)
    parser.add_option("-i", "--interactive", dest="batch", action="store_false")
    parser.add_option("-b", "--batch", dest="batch", action="store_true",
      default=None)
    parser.add_option("-q", "--quiet", dest="verbose", action="store_false")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
      default=None)
    parser.add_option("-t", "--threaded", dest="threaded", action="store_true",
      default=True)
    parser.add_option("-u", "--unthreaded", dest="threaded",
      action="store_false")
    parser.add_option("-s", "--seed", dest="seed", type="int", default=None)
    parser.add_option("-f", "--file", dest="infile", default=None)
    parser.add_option("--__execed", dest="execed", action="store_true",
      default=False)

    (opts, scriptargs) = parser.parse_args()
    if len(scriptargs) > 0:
        if scriptargs[0] != "-":
            opts.infile = scriptargs[0]
            scriptargs.pop(0)

        if len(scriptargs) > 0 and scriptargs[0] == "-":
            scriptargs.pop(0)
    opts.scriptargs = scriptargs

    if opts.help:
        print helpformatter.format_usage("")
        sys.exit(0)

    if opts.doc:
        help(opts.doc)
        sys.exit(0)

    if opts.version:
        print "Crux, version 1.2.0"
        sys.exit(0)

    if opts.infile is None:
        # Default to interactive/verbose.
        if opts.batch is None:
            opts.batch = False
        if opts.verbose is None:
            opts.verbose = True
    else:
        # Default to batch/quiet.
        if opts.batch is None:
            opts.batch = True
        if opts.verbose is None:
            opts.verbose = False

    return opts

#===============================================================================
# Beginning of main execution.
#

# Parse command line options.
opts = parse_options()

if not opts.batch:
    if not opts.execed:
        # Precursor to interactive mode.
        #
        # In order for interactive command line editing to work in its full
        # glory, it is necessary to exec the python interpreter, such that
        # interactive mode is enabled via python's '-i' flag.
        args = sys.argv[:]

        # Insert --__execed as the first command line argument.  Appending
        # doesn't work correctly when there are trailing script arguments.
        args.insert(1, "--__execed")

        args.insert(0, "/usr/local/bin/python2.6")
        args.insert(1, "-i")
        if len(" -O".strip()) > 0:
            args.insert(1, " -O".strip())

        # Re-launch python.
        os.execv("/usr/local/bin/python2.6", args)
        # Not reached.

    # Set the prompt.
    sys.ps1 = "crux> "
    sys.ps2 = "crux: "

# Copy configuration to Crux.Config.
Crux.Config.batch = opts.batch
Crux.Config.verbose = opts.verbose
if opts.threaded:
    Crux.threaded()
if opts.seed is not None:
    Crux.seed(opts.seed)
Crux.Config.infile = opts.infile
Crux.Config.scriptargs = opts.scriptargs

# Print various info if in verbose mode.
if Crux.Config.verbose:
    print "Crux, version: 1.2.0, %s, PID: %d, PRNG seed: %d" % \
      (("threaded" if Crux.Config.threaded else "unthreaded"), os.getpid(),
      Crux.Config.seed)

    if len(Crux.Config.scriptargs) != 0:
        print "Script argument%s: %s" % \
          (("s" if len(Crux.Config.scriptargs) != 1 else ""), \
          Crux.Config.scriptargs)

# Do batch processing.
if Crux.Config.verbose and Crux.Config.batch:
    print "Begin batch processing, %s" \
          % time.strftime("%Y/%m/%d %H:%M:%S (%Z)",
                          time.localtime(time.time()))

    if Crux.Config.infile is None:
        print "Input file: <stdin>"
    else:
        print "Input file: '%s'" % Crux.Config.infile


if Crux.Config.infile is not None:
    execfile(Crux.Config.infile)
elif Crux.Config.batch:
    exec(sys.stdin)

if Crux.Config.verbose:
    if Crux.Config.batch:
        print "End batch processing, %s" \
          % time.strftime("%Y/%m/%d %H:%M:%S (%Z)", time.localtime(time.time()))
    else:
        print "For Crux documentation, type: help(Crux)"
