#!/usr/bin/env python

import urllib
import json

from urllib2 import urlopen

bots_names = [
    "WPE Linux 64-bit Release (Build)",
    "WPE Linux 64-bit Debug (Build)",
    "GTK Linux 64-bit Release (Build)",
    "GTK Linux 64-bit Debug (Build)",
]

def last_build_url(bot_name):
    return "https://build.webkit.org/json/builders/%s/builds?select=-2&as_text=1" % urllib.quote(bot_name)

def short_comment(c):
    lines = []
    for line in c.splitlines():
        if line.startswith("Reviewed by"):
            break
        lines.append(line)
    return " ".join(lines)

def commit_message(t):
    comments = short_comment(t["comments"])
    revision = t["revision"]
    at = t["at"]
    who = t["who"]
    return "r%s: %s(%s, %s)" % (str(revision), comments, at, who)

def build_failed(r):
    status = r['text'][0]
    return status == 'failed'

def build_bot_message(r):
    builderName, number = (r['builderName'], r['number'])
    build_url = "https://build.webkit.org/builders/%s/builds/%d" % (urllib.quote(builderName), number)
    status = r['text'][0]
    msg = ["%s %s (%s)" % (builderName, status, build_url)]
    if build_failed(r):
        step = r['text'][1]
        if step == 'compile':
            change = r['sourceStamp']['changes'][0]
            msg.append(commit_message(change))
    return "\n".join(msg)

def query(url):
    try:
        response = urlopen(url)
        data = response.read().decode("utf-8")
        return json.loads(data)
    except:
        return None

if __name__ == '__main__':
    for each in bots_names:
        response = query(last_build_url(each))
        if response:
            print(build_bot_message(response['-2']))