#!/usr/bin/python
import portage,portage_dep,string,sys

args = sys.argv[1:]

if len(args) == 0:
	print "must supply at least one cat/pkg!"
	sys.exit(1)

all_mode=False
if "-a" in args:
	all_mode=True
	args.remove("-a")

print "looking for %s" % args
if all_mode:
	print "must match all"

def strip(str):
	try:	str = portage.pkgsplit(str)[0]
	except: return str
	while str[0] in ["!","~",">","=","<"]:
		str = str[1:]
	return str

def non_use(str):
	return str[-1] != "?" and str != "||"

cpv = portage.portdb.cp_all()
for y in cpv:
	match = portage.portdb.xmatch("match-all",y)
	for x in match:
		match_count = 0
		deps = portage.unique_array(map(strip,filter( \
			non_use,portage.flatten( \
			portage_dep.paren_reduce(string.join( \
			portage.portdb.aux_get(x,["RDEPEND"]) ))))))

		for a in args:
			if a in deps:
				if all_mode:
					match_count += 1
				else:
					print "match for "+a+" %s" % x
					break
		if match_count == len(args):
			print "match for %s" % x
sys.exit(0)
