#!/usr/bin/python
#
# Copyright (C) 2008 Emanuele Rocca <ema@debian.org>
#
# 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.

"""
List Ubuntu patches sorted by size
"""

import re
import os
import sys
import urllib2

URL = "http://patches.ubuntu.com/"

def a(href, text):
    return "<a href='%s'>%s</a>" % (href, text)

def lp_bts_url(pkg):
    return a('https://bugs.launchpad.net/ubuntu/+source/' + pkg, 'Ubuntu Bugs')

def deb_bts_url(pkg):
    return a('http://bugs.debian.org/' + pkg, 'Debian Bugs')

def debian_versions_dict():
    """-> Dictionary of Debian packages versions."""

    fd = open('/home/ema/public_html/SID-VERSIONS')
    # if the script doesn't run on gluck
    #fd = urllib2.urlopen('http://people.debian.org/~ema/SID-VERSIONS')
    packages = {}

    for line in fd.readlines():
        pkg, version = line.split()
        packages[pkg] = version

    return packages

def ubuntu_patches():
    """Ubuntu patches iterator. 
    Yields patch size, package name and patch URL."""

    packages = debian_versions_dict()
    for line in urllib2.urlopen(URL + 'PATCHES').readlines():
        pkg, patch = line.split()
        try:
            debian_version = packages[pkg]
        except KeyError:
            continue

        ubuntu_version = re.sub('ubuntu.*', '', patch.split('/')[2].split('_')[1])
        if debian_version == ubuntu_version:
            #print pkg

            size = int(urllib2.urlopen(URL + patch).info()['content-length'])
            yield (size, pkg, patch)

if __name__ == "__main__":
    try:
        output = sys.argv[1]
    except IndexError:
    	output = 'txt'

    patches = [ patch for patch in ubuntu_patches() ]

    patches.sort()
    
    if output == 'txt':
        for patch in patches:
            print patch[0], patch[1], URL + patch[2]

    elif output == 'html':
        for patch in patches:
	    print patch[0], a(URL + patch[2], os.path.basename(patch[2]))
	    print lp_bts_url(patch[1]) + ' '
	    print deb_bts_url(patch[1])
            print "\n<br />" 
