#!/usr/bin/env python
#
# This file is part of REPA: Release Engineering Process Assistant.
#
# Copyright (C) 2015 Intel Corporation
#
# REPA is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

"""
REPA: Release Engineering Process Assistant.

Copyright (C) Intel Corporation 2015
Licence: GPL version 2
Author: Ed Bartosh <eduard.bartosh@intel.com>

Rebuild module.
Rebuild submissions.
"""

import sys

from collections import namedtuple

from repa.main import sub_main
from repa.jenkins import trigger_build
from repa.common import edit

class Rebuild(object):
    """Subcommand: rebuild submissions."""

    name = 'rebuild'
    description = 'Rebuild submission'
    help = description

    @staticmethod
    def add_arguments(parser, config):
        """Adds arguments to the parser. Called from [sub_]main."""
        parser.add_argument('submission', help='submission')
        parser.add_argument('-p', '--package', help='package')
        parser.add_argument('-c', '--comment', help='comment',
                            default=config.get('rebuild_comment', ''))
        parser.add_argument('-e', '--edit', action='store_true',
                            help='run editor to edit comment')

    @staticmethod
    def run(argv):
        """Command line entry point. Called from [sub_]main."""
        if argv.edit:
            argv.comment = edit(argv.comment)
        job = 're'
        cred = namedtuple('cred', ['url', 'username', 'password'])(\
                   argv.jenkins_url, argv.jenkins_user, argv.jenkins_passwd)
        build, status, out = \
            trigger_build(job, {'action': 'rebuild',
                                'submission': argv.submission,
                                'package': argv.package,
                                'target_project': argv.project,
                                'comment': argv.comment}, cred)
        print "Jenkins job: %s, build #%s, status: %s" % (job, build, status)
        print out
        return status == 'SUCCESS'

if __name__ == '__main__':
    sys.exit(sub_main(sys.argv[1:], Rebuild()))
