#!/usr/bin/env python

### Preamble: allow this program to be run without PYTHON_PATH abuse
import sys, os
testsuite = os.path.split(os.path.abspath(sys.argv[0]))[0]
if testsuite not in sys.path:
    sys.path.insert(0, testsuite)
del sys, os, testsuite
### end of preamble

import getopt
import os
import re
import sys
import time
import traceback
from harness import log
from harness import server
from harness import testsuite
from harness import util

conn = "jk2"
spawn = 1
tests = 1

usage = """\
Usage: %s [OPTION...] [TESTS]

  -c, --connector=CONN    use the specified connector (default %s)
  -n, --nospawn           do not start a server (expects one to be running)
  -s, --server            don't run any tests, just spawn a server and wait
""" % (sys.argv[0], conn)

try:
    opts, args = getopt.getopt(
        sys.argv[1:], "c:ns", ["help", "connector=", "nospawn", "server"])
except getopt.GetoptError:
    print usage
    sys.exit(1)

for o, a in opts:
    if o == "--help":
        print usage
        sys.exit()
    if o in ("-c", "--connector"):
        conn = a
    if o in ("-n", "--nospawn"):
        spawn = 0
    if o in ("-s", "--server"):
        tests = 0

if not tests:
    if not spawn:
        print >>sys.stderr, "--nospawn and --server are mutually exclusive"
        sys.exit(1)
    if len(args):
        print usage
        sys.exit(1)

try:
    try:
        if tests:
            util.makeAll(testsuite.testdir)
        server.spawn = spawn
        server.getServer(conn)
        if tests:
            success = testsuite.runTests(args)
        else:
            log.info("press CTRL-C to stop...")
            try:
                while 1:
                    time.sleep(60)
            except:
                pass
            success = 1
    except:
        stripdir_re = re.compile(r'File "%s/' % os.getcwd())
        msg = "".join(apply(traceback.format_exception, sys.exc_info()))
        for line in msg.rstrip().split("\n"):
            log.error(stripdir_re.sub('File "', line.rstrip()))
        success = 0

finally:
    del server.server # XXX this should not be necessary

sys.exit(not success)
