#!/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>

Jenkins module. Triggering Jenkins builds.
"""

from jenkinsapi.jenkins import Jenkins
from requests import HTTPError, ConnectionError

class JenkinsError(Exception):
    """Local exception."""
    pass

def trigger_build(job, parameters, cred, block=True):
    """
    Trigger Jenkins build.

    :param job: job name
    :type job: string
    :param parameters: job parameters
    :type parameters: dictionary
    :param cred: credentials
    :type cred: named tuple cred.url, cred.username, cred.password
    :param block: block the call until build is finished
    :type block: bool
    :returns: build number, build status, console output
    """
    try:
        jenkins = Jenkins(cred.url, cred.username, cred.password)
    except (HTTPError, ConnectionError) as error:
        raise JenkinsError("Can't connect to jenkins: %s" % str(error))

    if job not in jenkins:
        raise JenkinsError("Job %s doesn't exist" % job)

    qitem = jenkins[job].invoke(block=block, build_params=parameters)
    build = qitem.get_build()
    return build.get_number(), build.get_status(), build.get_console()
