#!/usr/bin/python

# $Header: $
# This program is licensed under the GPL, version 2

import os,string,sys
sys.path.insert(0, "/usr/lib/gentoolkit/pym")
sys.path.insert(0, "/usr/lib/portage/pym")
from output import *
from getopt import getopt,GetoptError

__program__ = "glsa-update"
__author__ = "Ned Ludd <solar@gentoo.org>"
__version__ = "0.1"



nocolor()

# option parsing
args = []
params = ["affected"]
#params.append("affected")

# delay this for speed increase
from glsa import *

glsaconfig = checkconfig(portage.config(clone=portage.settings))

# Check that we really have a glsa dir to work on
if not (os.path.exists(glsaconfig["GLSA_DIR"]) and os.path.isdir(glsaconfig["GLSA_DIR"])):
	sys.stderr.write(red("ERROR")+": GLSA_DIR %s doesn't exist. Please fix this.\n" % glsaconfig["GLSA_DIR"])
	sys.exit(1)

# build glsa lists
completelist = get_glsa_list(glsaconfig["GLSA_DIR"], glsaconfig)

if os.access(glsaconfig["CHECKFILE"], os.R_OK):
	checklist = [line.strip() for line in open(glsaconfig["CHECKFILE"], "r").readlines()]
else:
	checklist = []
todolist = [e for e in completelist if e not in checklist]

glsalist = []

# maybe this should be todolist instead
for x in completelist:
	try:
		myglsa = Glsa(x, glsaconfig)
	except (GlsaTypeException, GlsaFormatException), e:
		continue
	if myglsa.isVulnerable():
		glsalist.append(x)

# remove invalid parameters
for p in params[:]:
	if not (p in completelist or os.path.exists(p)):
		#sys.stderr.write(("(removing %s from parameter list as it isn't a valid GLSA specification)\n" % p))
		params.remove(p)

glsalist.extend([g for g in params if g not in glsalist])

def fetchpkg(pkg):
	if os.path.exists("/usr/bin/qmerge"):
		try:
			os.system("qmerge -Cf " + pkg + " 2> /dev/null | grep MD5: | grep -q '[OK]'")
			try:
				os.system("emerge -qpvk "+pkg)
				#os.system("emerge -qpvk "+pkg)
			except:
				pass
		except:
			sys.write.stderr("Failed to fetch "+pkg )
			pass
	else:
		sys.write.stderr("qmerge is not installed; unable to d/l "+pkg )

pkglist=[]
for myid in glsalist:
	try:
		myglsa = Glsa(myid, glsaconfig)
	except (GlsaTypeException, GlsaFormatException), e:
		continue

	for pkg in myglsa.packages.keys():
		mylist = portage.db["/"]["vartree"].dbapi.match(portage.dep_getkey(pkg))
		if len(mylist) > 0:
			for x in mylist:
				cpv = portage.catpkgsplit(x)
				x = cpv[0]+ "/" + cpv[1]
				if x not in pkglist:
					pkglist.append(x)
		else:
			if pkg not in pkglist:
				pkglist.append(pkg)

		for x in pkglist:
			fetchpkg(x)

sys.exit(0)
