#!/usr/bin/env python

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import argparse
import os
import subprocess
import sys

sys.dont_write_bytecode = True

from common import testinfra
from common import testpulltask
from common import testimagetask

def main():
    parser = argparse.ArgumentParser(description='Perform next testing task from Github')
    parser.add_argument('-j', '--jobs', dest="jobs", type=int,
                        default=os.environ.get("TEST_JOBS", 1), help="Number of concurrent jobs")
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='Verbose output')
    parser.add_argument('--publish', dest='publish', action='store',
                        help='Publish results centrally to a sink')
    parser.add_argument('--head', dest='head', action='store_true',
                        help='Instead of choosing from GitHub, perform the specified task on HEAD')
    parser.add_argument('--refresh', action='store',
                        help='Instead of choosing from GitHub, refresh the given image')
    parser.add_argument('--except', dest='except_context', action='store_true',
                        help='Choose tasks from any context except the one specified')
    parser.add_argument('context', action='store', nargs='?',
                        help='The test context to choose tasks from')
    opts = parser.parse_args()

    os.chdir(os.path.dirname(__file__))
    github = testinfra.GitHub()

    # When letting github decide what to test
    if opts.head:
        name = "test"
        revision = subprocess.check_output([ "git", "rev-parse", "HEAD" ]).strip()
        context = opts.context or "verify/" + testinfra.DEFAULT_IMAGE
        task = testpulltask.GithubPullTask("test", revision, None, context)
    elif opts.refresh:
        image = opts.refresh
        config = testinfra.DEFAULT_IMAGE_REFRESH.get(image, None)
        if not config:
            print "Unknown image:", image
            return 1
        task = testimagetask.GithubImageTask("refresh-" + image, image, config, None)
    else:
        sys.stderr.write("Talking to GitHub ...\n")
        task_entries = github.scan(opts.publish, opts.context, opts.except_context)
        if len(task_entries) > 0:
            task = task_entries[0].task
        else: # Nothing to test
            return 1

    task.run(opts, github)

    return 0

if __name__ == '__main__':
    sys.exit(main())
