#!/usr/bin/python

import glob
import gtk
import gzip
import os
import subprocess
import sys
import urllib

def get_icon_cache(menudir):
    icons = gtk.icon_theme_get_default()
    icons.set_search_path([os.path.join(menudir, "icons"),
                           "/usr/share/icons/hicolor",
                           "/usr/share/icons/gnome",
                           ])
    return icons


if __name__ == "__main__":
    
    menudir = sys.argv[1]
    distroseries = sys.argv[2]

    icons = get_icon_cache(menudir)

    # gather what is missing
    missing = set()
    for dentry in glob.glob("%s/*.desktop" % menudir):
        pkgname = None
        for line in open(dentry):
            if line.startswith("Icon"):
                iconname_raw = line.strip().partition("=")[2]
                iconname = os.path.splitext(iconname_raw)[0]
                if iconname and not icons.has_icon(iconname):
                    #print "missing icon: '%s' in '%s'" % (iconname, dentry)
                    if iconname_raw.startswith("_"):
                        # convert "_" back to "/"
                        iconname_raw = iconname_raw.replace("_", "/")
                        # contents file comits the leading "/"
                        iconname_raw = iconname_raw[1:]
                    missing.add(iconname_raw)
    #print len(missing)

    # go over the missing ones using the Contents file
    contents = "Contents-i386.gz"
    subprocess.call(["wget", "-c", 
                     "http://archive.ubuntu.com/ubuntu/dists/%s/%s" % (
                distroseries, contents)])
    
    all_finds = {}
    for line in gzip.open(contents):
        (path, sep, component_section_packages) = line.strip().partition(" ")
        basename = os.path.basename(path)
        extension = os.path.splitext(basename)[1]
        if not extension in (".svg", ".png", ".xpm", ".tiff"):
            continue
        found = None
        if path in missing:
            #print "found full path '%s' in '%s'" % (path, component_section_packages)
            missing.remove(path)
            found = path
        elif basename in missing:
            #print "found basename '%s' in '%s'" % (path, component_section_packages)       
            missing.remove(basename)
            found = basename
        elif os.path.splitext(basename)[0] in missing:
            #print "found basename with no extension '%s' in '%s'" % (path, component_section_packages)
            missing.remove(os.path.splitext(basename)[0])
            found = os.path.splitext(basename)[0]
        if found:
            pkgname = os.path.basename(component_section_packages)
            if "icon-theme" in pkgname:
                continue
            if not pkgname in all_finds:
                all_finds[pkgname] = []
            all_finds[pkgname].append(found)

    print "pkgname -> icons"
    print all_finds
