#!/usr/bin/python

try:
    import autotest.common  # pylint: disable=W0611
except ImportError:
    import common  # pylint: disable=W0611
import fcntl
import os
import subprocess
import sys

from autotest.client import os_dep

try:
    autotest = os_dep.command('autotest-local')
except ValueError:
    bindir = os.path.dirname(__file__)
    autotest = os.path.join(bindir, 'autotest-local')

logdir = sys.argv[1]


# We want to simulate the behaviour of autotest_client, where fd3 would be
# routed to stderr and fd1 & fd2 to stdout

# HACK: grab fd3 for now
os.dup2(2, 3)

# open up log files to use for std*
stdout = open(os.path.join(logdir, 'stdout'), 'a', 0)
stderr = open(os.path.join(logdir, 'stderr'), 'a', 0)

# set up the file descriptors now, simulating the old behaviour
os.dup2(stdout.fileno(), 1)
os.dup2(stdout.fileno(), 2)
os.dup2(stderr.fileno(), 3)

# we don't need the file objects any more
stdout.close()
stderr.close()


args = [autotest] + sys.argv[2:]
if '-H' not in args:
    args[1:1] = ['-H', 'autoserv']
cmd = ' '.join(args)

# open up a log file for saving off the exit code
exit_file = open(os.path.join(logdir, 'exit_code'), 'w', 0)
fcntl.flock(exit_file, fcntl.LOCK_EX)

# touch a 'started' file to indicate we've been initialized
open(os.path.join(logdir, 'started'), 'w').close()

# run the actual autotest client and write the exit code into the log file
exit_code = subprocess.call(cmd, shell=True)
exit_file.write('%+04d' % exit_code)
exit_file.flush()
fcntl.flock(exit_file, fcntl.LOCK_UN)
exit_file.close()
