#!/usr/bin/python

# find out which job, of a jenkins-job-builder yaml definition file,
# needs triggering due to the given git commit.

# Copyright 2013 Peter Palfrader
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import sys,yaml

BRANCHPREFIX='refs/heads/'

if len(sys.argv) != 3:
    print >> sys.stderr, "Usage: cat <jobs.yaml> |  %s <git ref file> <url>"%(sys.argv[0])
    sys.exit(2)

gitreffn = sys.argv[1]
url = sys.argv[2]
if not url.endswith('.git'): url += ".git"

# learn which branches have been changed
changed = {}
with open(gitreffn) as gitref:
    for line in gitref:
        a = line.split()
        if len(a) < 3: continue
        digest, ref = a[1:3]
        if ref.startswith(BRANCHPREFIX):
            ref = ref[len(BRANCHPREFIX):]

        if ref not in changed:
            changed[ref] = digest

f = yaml.load(sys.stdin)
for entry in f:
    if not 'job' in entry: continue
    job = entry['job']
    if not 'scm' in job: continue
    for scm in job['scm']:
        if not 'git' in scm: continue
        git = scm['git']
        if not 'url' in git: continue

        joburl = git['url']
        if not joburl.endswith('.git'): joburl += ".git"

        if joburl != url: continue
        if not 'branches' in git: continue
        for b in git['branches']:
            if b in changed:
                print job['name'], b, changed[b]
