#!/usr/bin/python

# written by Torsten Rehn <torsten@rehn.tel>
# published into the public domain

URL_REV = "http://build.chromium.org/buildbot/continuous/mac/LATEST/REVISION"
URL_ZIP = "http://build.chromium.org/buildbot/continuous/mac/LATEST/chrome-mac.zip"
TMP_DIR = "/tmp/chromium-update/"
CHROMIUM_PATH = "/Applications/Chromium.app/"

import re
from os import system
from sys import exit
from urllib2 import urlopen, HTTPError

def get_latest_rev():
	try:
		u = urlopen(URL_REV)
	except HTTPError:
		return None
	try:
		rev = int(u.read().strip())
	except ValueError:
		return None
	return rev

def get_installed_rev():
	# who parses XML anyway
	f = open(CHROMIUM_PATH + "Contents/Info.plist")
	lines = f.readlines()
	f.close()
	found_rev = False
	rev = None
	for line in lines:
		if found_rev is False and line.strip() == "<key>SVNRevision</key>":
			found_rev = True
		if found_rev is True:
			match = re.match(r"\<string\>(\d+)\</string\>", line.strip())
			if match:
				rev = int(match.group(1))
				break
	return rev

if __name__ == "__main__":
	print "Latest revision...",
	latest = get_latest_rev()
	if latest:
		print latest
	else:
		print "not found!"
	
	print "Installed revision...",
	installed = get_installed_rev()
	if installed:
		print installed
	else:
		print "not found!"
	
	if installed >= latest:
		print "No update available"
		exit(0)

	print "All Chromium processes will be terminated. Continue with update? [Y/n] ",
	input = raw_input()
	if input != "" and input != "y":
		exit(0)
	
	system("killall Chromium")
	system("rm -rf " + CHROMIUM_PATH)
	system("rm -rf " + TMP_DIR)
	system("mkdir -p " + TMP_DIR)
	system("wget " + URL_ZIP + " -O " + TMP_DIR + "chrome.zip")
	system("unzip -d " + TMP_DIR + " " + TMP_DIR + "chrome.zip")
	system("mv " + TMP_DIR + "chrome-mac/Chromium.app " + CHROMIUM_PATH)
	system("rm -rf " + TMP_DIR)
	
	print "Update complete"