#!/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('-n', '--name', dest='name',
                        default='pull', help='Name of the testing task, used for the identifier. Examples: "master", "pull-1234"')
    parser.add_argument('-o', '--offline', action='store_true',
                        help='Work offline, don''t fetch new data from origin for rebase')
    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__))

    # only instantiate a GitHub object if we aren't working offline
    github = None if opts.offline else 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
        name = opts.name or "test"
        task = testpulltask.GithubPullTask(name, 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:
        if opts.offline:
            print "Unable to contact GitHub in offline mode"
            return 1
        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

    ret = task.run(opts, github)
    if isinstance(ret, basestring):
        print ret
        return 1
    return ret

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