#!/usr/bin/env python

import urllib2
import base64
import sys
import os
import ast

def get_build_data(url):
    req = urllib2.Request(url = url)

    username = os.environ.get('BUILDER_USERNAME')
    password = os.environ.get('BUILDER_PASSWORD')
    if username and password:
        auth = base64.standard_b64encode("%s:%s" % (username, password))
        req.add_header("Authorization", "Basic %s" % auth)

    return ast.literal_eval(urllib2.urlopen(req).read())

# get the primary build's data
data = get_build_data(sys.argv[1])

# TODO: other more interesting stuff?
meta_vars = ["number", "result"]
for var in meta_vars:
    print "BUILD_META_%s=%s" % (var.upper(), data[var])

try:
    changes = []
    last_build = int(sys.argv[2])
    for build in xrange(last_build + 1, data['number'] + 1):
        build_url = sys.argv[1].replace('lastSuccessfulBuild', str(build))
        build_url = build_url.replace(str(data['number']), str(build))
        build_data = get_build_data(build_url)
        changes += [i['msg'].replace('"','') for i in build_data['changeSet']['items']]
    print 'BUILD_META_CHANGES="%s"' % "\\n".join(changes)
except IndexError:
    print 'BUILD_META_CHANGES="None. First deployment?"'
