#!/usr/bin/python
# quick script to check which desktop files refer to packages that are no longer in the cache
# beware that apps only available on i386, but not on amd64 are also listed when running on amd64

import glob
import os
import sys

from apt.cache import Cache
from glob import glob

if len(sys.argv) < 2:
    basepath = "."
else:
    basepath = sys.argv[1]

cache = Cache()
cache.open()

pkg_count = 0

for entry in os.listdir(basepath):
    # we only care for folders that start with menu-data
    if not (entry.startswith("menu-data") and
            os.path.isdir(os.path.join(basepath, entry))):
        continue
    # now check all the desktop files in there
    for desktop_file_path in glob(os.path.join(basepath, entry,"*.desktop")):
        pkgname = None
        component = None
        for line in open(desktop_file_path):
            if line.startswith("X-AppInstall-Package="):
                pkgname = line[len("X-AppInstall-Package="):].strip('\n')
            elif line.startswith("X-AppInstall-Section="):
                component = line[len("X-AppInstall-Section="):].strip('\n')
        try:
            pkg = cache[pkgname]
            if not "/" in pkg.section:
                pkg_component = "main"
            else:
                pkg_component = pkg.section.split("/")[0]
            if pkg_component != component:
                print "%s: component mismatch pkg=%s vs meta=%s" % (
                    desktop_file_path, pkg_component, component)
        except KeyError:
            pkg_count += 1
            print "not in cache: %s" % desktop_file_path

print str(pkg_count) + " desktop files can be removed."
