#!/usr/bin/python

# Copyright (c) 2016 SUSE LINUX GmbH, Nuernberg, Germany.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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.

# Triggers a jenkins job via the API
# Needed for job chains that are not possible to implement natively

import jenkins
import json
import os
import sys


def usage():
    print("Error: No job name defined as first parameter.\n" +
              "Add parameters as needed:\n" +
              "  jenkins-job-trigger <job_name> [ para1=val1 [ para2=val2 ]... ]")
    sys.exit(1)

def jenkins_build_job(job_name, job_args=[]):
    if not job_name:
        usage()

    config_files = ('/etc/jenkinsapi.conf', './jenkinsapi.conf')
    config = dict()
    job_parameters = dict()

    for config_file in config_files:
        if not os.path.exists(config_file):
            continue
        with open(config_file, 'r') as f:
            config.update(json.load(f))

    if not config:
        print('Error: No config file could be loaded. Please create either of: %s' %
              ', '.join(config_files))
        sys.exit(1)

    for param in job_args:
        # backwards compatibility, ignore -p and -m
        if param in ('-p', '-m'):
            continue
        p_key, _, p_val = param.partition('=')
        job_parameters[p_key.strip(' ')] = p_val.strip(' ')

    server = jenkins.Jenkins(str(config['jenkins_url']),
                             username=config['jenkins_user'],
                             password=config['jenkins_api_token'])
    server.build_job(job_name, job_parameters)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
    args = list()
    if len(sys.argv) > 2:
        args.extend(sys.argv[2:])
    jenkins_build_job(sys.argv[1], args)
