#!/usr/bin/env python3

import os
import sys
import posixpath
import subprocess

from optparse import OptionParser


DEFAULT_DIRECTORY = "/tmp/checkbox.cking-scripts"
DEFAULT_LOCATION = "git://kernel.ubuntu.com/cking/scripts"

COMMAND_TEMPLATE = "cd %(scripts)s; ./%(script)s"


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.items():
        print_line(key, value)

    print()


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

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

    process = subprocess.Popen(["git", "clone", location, directory],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    if process.wait():
        raise Exception("Failed to clone cking scripts from %s" % location)


def run_cking_scripts(scripts, location, directory, dry_run):
    if not dry_run:
        clone_cking_scripts(location, directory)

    for script in scripts:
        path = posixpath.join(directory, script)

        # Initialize test structure
        test = {}
        test["plugin"] = "shell"
        test["name"] = posixpath.splitext(posixpath.basename(path))[0]
        test["command"] = COMMAND_TEMPLATE % {
            "scripts": posixpath.dirname(path),
            "script": posixpath.basename(path)}

        # Get description from first line of the README file
        readme_path = posixpath.join(posixpath.dirname(path), "README")
        if os.path.exists(readme_path):
            file = open(readme_path)
            test["description"] = file.readline().strip()
            file.close
        else:
            test["description"] = "No description found"

        yield test


def main(args):
    usage = "Usage: %prog [OPTIONS] [SCRIPTS]"
    parser = OptionParser(usage=usage)
    parser.add_option("--dry-run",
        default=False,
        action="store_true",
        help="Dry run to avoid branching from the given location.")
    parser.add_option("-d", "--directory",
        default=DEFAULT_DIRECTORY,
        help="Directory where to branch qa-regression-testing")
    parser.add_option("-l", "--location",
        default=DEFAULT_LOCATION,
        help="Location from where to branch qa-regression-testing")

    (options, scripts) = parser.parse_args(args)

    if not scripts:
        parser.error("Must specify a script")

    tests = run_cking_scripts(scripts, options.location, options.directory,
        options.dry_run)
    if not tests:
        return 1

    for test in tests:
        print_element(test)

    return 0

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