# -*- coding: utf-8 -*-

import sys
import os
from subprocess import Popen

test_args = []
cmd_args = []

def remove_file(name):
  try:
    os.unlink(name)
  except Exception:
    pass

def parse_args():
  """Parse the command line, searching for test-specific arguments and program
     specific arguments."""
  global test_args
  global cmd_args

  # Split argument streams for subsequent analysis.
  for i in sys.argv[1:]:
    if i[:6] == "--test":
      test_args.append(i)
    else:
      cmd_args.append(i)

def run_program(stage, args):
  """Run the given command with arguments, storing output and erros in the
     files stage-out and stage-err, respectively. The command executed is
     stored in a file stage-cmd. """
  cmd = file("%s-cmd" % stage, "w")
  cmd.write(" ".join(args))
  cmd.close()

  out = file("%s-out" % stage, "w")
  err = file("%s-err" % stage, "w")
  cc = Popen(args, stdout=out, stderr=err)
  ret = cc.wait()
  out.close()
  err.close()
  return ret

def read_file(name):
  f = file(name, "r")
  txt = f.read()
  f.close()
  return txt

def stage_cmd(stage):
  return read_file("%s-cmd" % stage)

def stage_err(stage):
  return read_file("%s-err" % stage)

def exit_failure():
  f = file("test-failure", "w")
  sys.exit(0)

def exit_success():
  """Exit the test case, indicating success. A file named test-success is
     created in the local directory."""
  f = file("test-success", "w")
  sys.exit(0)

# As we start, unlink any previous test-* files. This ensures that the
# directory will only ever contain the most recent test results
remove_file("test-success")
remove_file("test-failure")


