#!/usr/bin/python

import os
import sys
import logging
import posixpath

from optparse import OptionParser
from urlparse import urlparse


DEFAULT_DIRECTORY = "/var/cache/checkbox/autotest"
DEFAULT_LOCATION = "http://test.kernel.org/svn/autotest/trunk/client/"
DEFAULT_TIMEOUT = 900

COMMAND_TEMPLATE = "%(directory)s/bin/autotest %(directory)s/tests/%(test)s/control 2>/dev/null | autotest_filter --suite=autotest"


def print_line(key, value):
    if type(value) is list:
        print "%s:" % key
        for v in value:
            print " %s" % v
    else:
        print "%s: %s" % (key, value)

def print_element(element):
    for key, value in element.iteritems():
        print_line(key, value)

    print

def fetch_autotest(location, directory):
    if posixpath.exists(directory):
        return

    dirname = posixpath.dirname(directory)
    if not posixpath.exists(dirname):
        os.makedirs(dirname)

    autotest_path = urlparse(location)[2]
    cut_dirs = len(autotest_path.strip(posixpath.sep).split(posixpath.sep))

    command = "wget -q -e robots=off -R index.html -np -nH --cut-dirs=%d -P %s -r %s" \
        % (cut_dirs, directory, location)
    logging.info("Running command: %s" % command)
    if os.system(command) != 0:
        raise Exception, "Failed to run command: %s" % command

    # Change mode of binary files
    directories = [posixpath.join(directory, d)
        for d in "bin", "common_lib", "deps", "profilers",
                 "samples", "tests", "tools"]
    while directories:
        directory = directories.pop()
        for name in os.listdir(directory):
            path = posixpath.join(directory, name)
            if posixpath.isfile(path) \
               and name is not "control":
                os.chmod(path, 0755)
            elif posixpath.isdir(path):
                directories.append(path)

def list_autotest(location, directory):
    fetch_autotest(location, directory)

    directory = posixpath.join(directory, "tests")
    return os.listdir(directory)

def run_autotest(names, location, directory, timeout=None):
    fetch_autotest(location, directory)

    for name in names:
        path = posixpath.join(directory, "tests", name)

        # Initialize test structure
        test = {}
        test["plugin"] = "remote"
        test["depends"] = "autotest"
        test["timeout"] = timeout
        test["name"] = name
        test["user"] = "root"
        test["command"] = COMMAND_TEMPLATE % {
            "directory": directory,
            "test": name}

        yield test

def main(args):
    usage = "Usage: %prog [OPTIONS] [NAMES]"
    parser = OptionParser(usage=usage)
    parser.add_option("-d", "--directory",
        default=DEFAULT_DIRECTORY,
        help="Directory where to branch autotest")
    parser.add_option("-l", "--location",
        default=DEFAULT_LOCATION,
        help="Location from where to checkout autotest")
    parser.add_option("-t", "--timeout",
        default=DEFAULT_TIMEOUT,
        type="int",
        help="Timeout when running autotest")
    (options, names) = parser.parse_args(args)

    if not names:
        names = list_autotest(options.location, options.directory)

    suites = run_autotest(names, options.location, options.directory, options.timeout)
    if not suites:
        return 1

    for suite in suites:
        print_element(suite)

    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
