#!/usr/bin/python
#
# Copyright (C) 2005-2007 Canonical (Author: Michael Vogt)
# Copyright (C) 2007-2008 Julian Andres Klode <jak@jak-linux.org>
#
# This package 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; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import glob
import urllib2
from optparse import OptionParser


def extractPopconData(filename):
	res = {}
	print 'Fetching Popcon Data'
	for line in urllib2.urlopen(filename):
		if line.startswith("#"):
			continue
		# we split until we reach the "------" line where we stop
		try:
			(rank, name, inst, vote, old, recent, files, maint) = line.split(None,7)
			# mvo: we use inst as the indicator (because we do not have enough
			#	  data to use vote
			res[name] = vote
		except ValueError:
			break
	return res

def mergePopconData(menudir, popcon_data):
	for dentry in sorted(glob.glob("%s/*.desktop" % menudir)):
		pkgname = None
		for line in open(dentry):
			if line.startswith("X-AppInstall-Package"):
				pkgname = line.strip().split("=")[1]
				if not popcon_data.has_key(pkgname):
					print "WARNING: no popcon data for '%s'" % pkgname
					pkgname = None
		if not pkgname is None:
			print "Updating '%s' with popcon data for '%s'" % (dentry,pkgname)
			content = []
			for line in open(dentry):
				if not line.startswith("X-AppInstall-Popcon="):
					content.append(line)
				if line.startswith("X-AppInstall-Package"):
					content.append("X-AppInstall-Popcon=%s\n" % popcon_data[pkgname])
			if not content[-1].endswith("\n"):
				content[-1] += "\n"
			f = open(dentry,"w")
			f.write("".join(content))
			f.close()

if __name__ == "__main__":
	parser = OptionParser()
	parser.add_option("-v", "--verbose", dest="verbose",
					  action="store_true", default="False",
					  help="be verbose")
	parser.add_option("-p", "--popcon-uri", dest="popcon_uri",
					  default="http://popcon.debian.org/by_vote",
					  help="download location for the popcon data")
	parser.add_option("-d", "--directory", dest="dir",
					  default="menu-data",
					  help="directory for the menu-data")
	(options, args) = parser.parse_args()

	# extract the data, popcon data is a dictionary with
	# (pkgname -> value) where big values are better
	popcon_data = extractPopconData(options.popcon_uri)

	# merge popcon data
	mergePopconData(options.dir, popcon_data)

