#!/usr/bin/env python2.2
import os,sys,portage,xpak,string,re,commands,time
from stat import *
from output import *

spinner="\|/-\|/-"
spinpos=0
#number of ebuilds merged
merged=0
actions=["clean",
	"config",
	"help",
	"prune",
	"rebuild",
	"rsync",
	"search",
	"sync",
	"system",
	"unmerge",
	"world",
	"inject"]
options=["--autoclean",
	"--clean",
	"--buildpkg",
	"--debug",
	"--nodeps",
	"--emptytree",
	"--fetchonly",
	"--noreplace",
	"--onlydeps",
	"--pretend",
	"--usepkg",
	"--verbose",
	"--update",
	"--help",
	"--oneshot",
	"--version"]

shortmapping={"a":"--autoclean",
	"b":"--buildpkg",
	"c":"clean",
	"C":"unmerge",
	"e":"--emptytree",
	"d":"--debug",
	"f":"--fetchonly",
	"h":"--help",
	"k":"--usepkg",
	"n":"--noreplace",
	"o":"--onlydeps",
	"p":"--pretend",
	"P":"prune",
	"s":"search",
	"u":"--update",
	"v":"--verbose",
	"V":"--version",
	"i":"inject"}
	
myaction=None
myopts=[]
myfiles=[]
edebug=0

# process short actions and options
tmpcmdline=sys.argv[1:]
tmpcmdline.extend(portage.settings["EMERGE_OPTS"].split())
cmdline=[]
for x in tmpcmdline:
	if x[0:1]=="-"and x[1:2]!="-":
		for y in x[1:]:
			if shortmapping.has_key(y):
				cmdline.append(shortmapping[y])
			else:
				print "!!! Error: -"+y+" is an invalid short action or option."
				sys.exit(1)
	else:
		cmdline.append(x)

# process the command arguments
for x in cmdline:
	if len(x)>=2 and x[0:2]=="--":
			if x in options:
				myopts.append(x)
			else:
				print "!!! Error:",x,"is an invalid option."
				sys.exit(1)
	elif (not myaction) and (x in actions):
		myaction=x
	else:	
		# this little conditional helps tab completion
		if x[-1]=="/":
			myfiles.append(x[:-1])
		else:
			myfiles.append(x)

# check if root user is the current user for the actions where emerge needs this
if os.getuid()!=0 and ("--help" not in myopts) and ("--version" not in myopts) and ("search"!=myaction):
	print "!!! to be able to perform the requested action, emerge must be run by root."
	sys.exit(1)

# search functionality
class search:
	
	#
	# class constants
	#
	VERSION_SHORT=1
	VERSION_RELEASE=2
	
	#
	# public interface
	#
	def __init__(self,searchkey=""):
		"""Searches the available and installed packages for the supplied search key.
		The list of available and installed packages is created at object instantiation.
		This makes successive searches faster."""
		self.searchkey = searchkey
		self.treecache = portage.portagetree()
		self.installcache = portage.vartree()
		self.re_portagedir = re.compile('/usr/portage/')
		self.re_description = re.compile('DESCRIPTION="')
		self.re_homepage = re.compile('HOMEPAGE="(.*)"')
		self.initResults()
		
	def setKey(self,searchkey):
		"""changes the search key"""
		self.searchkey = searchkey
		self.initResults()
	
	def execute(self):
		"""Performs the saerch for the supplied search key"""
		if self.searchkey:
			self.initResults()
			for package in self.treecache.getallnodes():
				package_parts=package.split("/")
				if package_parts:
					if self.searchkey != "*":
						if re.search(self.searchkey.lower(), package_parts[1].lower()):
							self.packagematches.append(package)
					else:
						self.packagematches.append(package)
			self.packagematches.sort()

	def output(self):
		"""Outputs the results of the search."""
		print "[ Results for search key : "+white(self.searchkey)+" ]"
		print "[ Applications found : "+white(str(len(self.packagematches)))+" ]"
		print " "
		for match in self.packagematches:
			full_package = string.strip(self.treecache.dep_bestmatch(match))
			if len(full_package) > 1:
				print green("*")+"  "+white(match)
				print "     ", "Latest version Available:",self.getVersion(full_package, search.VERSION_RELEASE)
				print "     ", self.getInstallationStatus(match)
				print "     ", "Homepage:",self.getHomepage(self.getFullPath(match, full_package))
				print "     ", "Description:",self.getDescription(self.getFullPath(match, full_package),self.getVersion(full_package, search.VERSION_SHORT))
				print " "
			else:
				print green("*")+"  "+white(match)+" "+red("[ Masked ]")
				print " "
		
	#
	# private interface
	#
	def initResults(self):
		self.packagematches = []
	
	def getInstallationStatus(self,package):
		installed_package = self.installcache.dep_bestmatch(package)
		result = ""
		version = self.getVersion(installed_package,search.VERSION_RELEASE)
		if len(version) > 1:
			result = "Latest version Installed: "+version
		else:
			result = "Latest version Installed: [ Not Installed ]"
		return result

	def getHomepage(self,ebuildPath):
		file = open(ebuildPath)
		result = "";
		indescription=0
		homepage="";
		while 1:
			data = file.readline()
			if data:
				homepage_match=self.re_homepage.match(data)
				if homepage_match:
					homepage=homepage_match.group(1)
					break;
			else:
				break;
		file.close()
		return homepage

	def getDescription(self,ebuildPath,packageVersion): ## Gets description from latest ebuild ##
		file = open(ebuildPath)
		result = "";
		indescription=0
		while 1:
			data = file.readline()
			if data:
				if self.re_description.match(data.upper()):
					indescription=1
					p = self.re_description.split(data)
					p = p[1].split('"')
					result = p[0].strip()
					if len(p)>1:
						break
				elif indescription==1:
					if '"' in data:
						p = data.split('"')
						result = result+" "+p[0].strip()
						indescription = 0
					else:
						result = result+" "+data.strip()
			else:
				break;
		file.close()
		result = string.replace(result, "${PV}", packageVersion)
		result = string.replace(result, "${pv}", packageVersion)
		result = string.replace(result, "${description}", "KDE "  + packageVersion + " ")
		result = string.replace(result, "\n", "")
		file.close()
		# format and wrap the description text nicely
		wraplength=60
		formatted_result=""
		while len(result)>wraplength:
			lineposition=0
			position=wraplength
			while result[lineposition+position]!=' ' and position != 0:
				position = position-1
			if position==0:
				position=wraplength
			if len(formatted_result)==0:
				formatted_result=result[:position]
			else:
				formatted_result=formatted_result+"\n      "+result[:position]
			result=result[position+1:]
			if wraplength==60:
				wraplength=73
		formatted_result=formatted_result+"\n      "+result
		return formatted_result

	def getFullPath(self,packageShortName,packageFullName):  ## Returns the full path of the ebuild ##
		absolute_path = '/usr/portage/' + packageShortName.strip()
		package_parts = packageFullName.split("/")
		result = absolute_path + "/" + package_parts[1] + ".ebuild"
		return result

	def getVersion(self,full_package,detail):
		if len(full_package) > 1:
			package_parts = portage.catpkgsplit(full_package)
			if detail == search.VERSION_RELEASE and package_parts[3] != 'r0':
				result = package_parts[2]+ "-" + package_parts[3]
			else:
				result = package_parts[2]
		else:
			result = ""
		return result

#build our package digraph
def getlist(mode):
	if mode=="system":
		if portage.profiledir:
			pfile=portage.profiledir+"/packages"
		else:
			print "!!! No profile directory; system mode unavailable."
			sys.exit(1)
	elif mode=="world":
		pfile=portage.root+"var/cache/edb/world"
	try:
		myfile=open(pfile,"r")
	except OSError:
		print "!!! Couldn't open "+pfile+"; exiting."
		sys.exit(1)
	mylines=myfile.readlines()
	myfile.close()
	mynewlines=[]
	for x in mylines:
		myline=string.join(string.split(x))
		if not len(myline):
			continue
		elif myline[0]=="#":
			continue
		elif mode=="system":
			if myline[0]!="*":
				continue
			myline=myline[1:]
		mynewlines.append(myline.strip())
	return mynewlines

def genericdict(mylist):
	mynewdict={}
	for x in mylist:
		if x[0] in ["=","~","!"]:
			mynew=x[1:]
		elif x[0:2] in [">=", "<=" ]:
			mynew=x[2:]
		elif x[0] in [">","<"]:
			mynew=x[1:]
		else:
			mynew=x
		if portage.isspecific(mynew):
			mysplit=portage.catpkgsplit(mynew)
			mynewdict[mysplit[0]+"/"+mysplit[1]]=x
		else:
			mynewdict[mynew]=x
	return mynewdict

def getworldlist():
	syslist=getlist("system")
	worldlist=getlist("world")
	sysdict=genericdict(syslist)
	worlddict=genericdict(worldlist)
	#we're effectively upgrading sysdict to contain all new deps from worlddict
	for x in worlddict.keys():
		#only add the world node if the package is:
		#actually installed -- this prevents the remerging of already unmerged packages when we do a world --update;
		#actually available -- this prevents emerge from bombing out due to no match being found (we want a silent ignore)
		if portage.db[portage.root]["vartree"].dep_match(x) and portage.db[portage.root]["porttree"].dep_match(x):
			#note: when implementing the "anti-dep" world profile entry feature, we will need to test for "!" deps and
			#*not* call dep_match() on those, as dep_match() doesn't expect ! deps (since nothing matches a !)
			sysdict[x]=worlddict[x]
	mylist=[]
	for x in sysdict.keys():
		mylist.append(sysdict[x])
	return mylist

class depgraph:

	def __init__(self,myaction,myopts):
		self.myaction=myaction
		self.myopts=myopts
		virts=portage.getvirtuals("/")
		self.digraph=portage.digraph()
		self.orderedkeys=[]
		#the following is so we have an empty vartree (used in emerge update calculations)
		self.emptytree=portage.vartree("/",virts,portage.db["/"]["vartree"])
		self.emptytree.tree={}
		self.emptytree.root=None
		if "--emptytree" in myopts:
			portage.db["/"]["vartree"].tree=self.emptytree.tree
			portage.db["/"]["vartree"].populated=1
			#The root needs to be set to "None" to enable "empty" mode
			#And this needs to be done before the inject() below, since inject causes recalc.
			#of USE variables, which causes our tree to become partially populated
			portage.db["/"]["vartree"].root=None
			portage.db["/"]["vartree"].inject("sys-libs/glibc-1.0")
			portage.db["/"]["vartree"].virtual={"virtual/glibc":"sys-libs/glibc"}
		self.outdatedpackages=[]

	def create(self,mybigkey,myparent=None,addme=1):
		"""creates the actual digraph of packages to merge.  return 1 on success, 0 on failure
		mybigkey = specification of package to merge; myparent = parent package (one depending on me);
		addme = should I be added to the tree? (for the --onlydeps mode)"""
		if mybigkey==None:
			return
		global spinner, spinpos
		sys.stdout.write("\b"+spinner[spinpos])
		spinpos=(spinpos+1)%8
		sys.stdout.flush()
		if self.digraph.hasnode(mybigkey):
			#if we've already hit this node before, we're already recursing on the dependencies.
			#no need to recurse again.
			if addme:
				if myparent:
					self.digraph.addnode(mybigkey,myparent)
			return 1
		mytype,myroot,mykey=string.split(mybigkey)
		if "--noreplace" in self.myopts or "--update" in self.myopts:
			if portage.db[myroot]["vartree"].exists_specific(mykey):
				#already merged, skip.
				return 1
		if mytype=="binary":
			if not portage.db[portage.root]["bintree"].exists_specific(mykey):
				print "\n\n!!!",mytype,mykey,"not found (possibly blocked by package.mask)\n"
				sys.exit(1)
			mypkgparts=portage.catpkgsplit(mykey)
			mytbz2=xpak.tbz2(portage.db[portage.root]["bintree"].getname(mykey))
			edepend=["",string.join(mytbz2.getelements("RDEPEND")," "),mytbz2.getfile("SLOT",mypkgparts[2])]
		elif mytype=="ebuild":
			if not portage.db[myroot]["porttree"].exists_specific(mykey):
				print "\n\n!!!",mytype,mykey,"not found (possibly blocked by package.mask)\n"
				sys.exit(1)
				mydep={}
			myebuild=portage.db[myroot]["porttree"].getname(mykey)
			mydbkey="/var/cache/edb/dep/dep-"+os.path.basename(myebuild)
			#use the cached info if it is available and more recent than the ebuild itself (mtime)
			dbstat=0
			regen=0
			try:
				dbstat=os.stat(mydbkey)[ST_MTIME]
			except OSError:
				regen=1
			if not regen:
				if dbstat<(os.stat(myebuild)[ST_MTIME]):
					regen=1
			if regen:
				portage.doebuild(myebuild,"depend",myroot,edebug)
			mydb=open(mydbkey,"r")
			edepend=eval(mydb.readline())
			mydb.close()
		elif mytype=="blocks":
			edepend=None
			parenttype,parentroot,parentkey=string.split(myparent)
			if portage.isspecific(mykey):
				if portage.db[myroot]["vartree"].exists_specific(mykey):
					if portage.db[myroot]["vartree"].resolve_key(mykey) != portage.db[myroot]["vartree"].resolve_key(parentkey):
						self.digraph.addnode(mybigkey,myparent)
			else:
				if portage.db[myroot]["vartree"].hasnode(mykey):
					parentsplit=portage.catpkgsplit(parentkey)
					parentkey=parentsplit[0]+"/"+parentsplit[1]
					if portage.db[myroot]["vartree"].resolve_key(mykey) != portage.db[myroot]["vartree"].resolve_key(parentkey):
						self.digraph.addnode(mybigkey,myparent)
					else:
						print "OK!"
		if edepend:
			mydep={}	
			if myroot=="/":
				mydep["/"]=edepend[0]+" "+edepend[1]
			else:
				# We can no longer do this: mydep["/"],mydep[myroot]=edepend
				# edepend now has more than 2 elements.
				mydep["/"]=edepend[0]
				mydep[myroot]=edepend[1]
			if addme:
				self.digraph.addnode(mybigkey,myparent)
			if "--nodeps" in self.myopts:
				return 1
			for dep in mydep.keys():
				if "--update" in self.myopts:
					mycheck=self.emptytree.depcheck(mydep[dep])
				else:
					mycheck=portage.db[dep]["vartree"].depcheck(mydep[dep])
				if mycheck[0]==0:
					if mytype=="binary":
						print "!!! Error merging",mytbz2+": invalid dependency in:"
					elif mytype=="ebuild":
						print "!!! Error merging",myebuild+": invalid dependency in:"
					else:
						print "!!! Error merging",mykey+": invalid dependency in:"
					print white("\n'"+mydep[dep]+"'")
					print ">>> Please report this ebuild error to http://bugs.gentoo.org.\n"
					return 0
				for x in mycheck[1]:
					mynew=self.match(x,dep,mykey)
					if not self.digraph.hasnode(mynew):
						if addme:
							if not self.create(mynew,mybigkey):
								return 0
						else:
							if not self.create(mynew,None):
								return 0
					else:
						self.digraph.addnode(mynew,mybigkey)

		return 1
	
	def altlist(self):
		mygraph=self.digraph.copy()
		dolist=["/"]
		retlist=[]
		for x in portage.db.keys():
			portage.db[x]["merge"]=[]
			if x not in dolist:
				dolist.append(x)
		while (not mygraph.empty()):
			mycurkey=mygraph.firstzero()
			if not mycurkey:
				print "!!! Error: circular dependencies:"
				print
				for x in mygraph.dict.keys():
					for y in mygraph.dict[x][1]:
						print y,"depends on",x
				print
				sys.exit(1)
			splitski=string.split(mycurkey)
			#I'm not sure of the significance of the following lines (vestigal?) so I'm commenting 'em out.
			#if "--update" in self.myopts:
			#if not portage.db["/"]["vartree"].exists_specific(splitski[2]):
			#	portage.db["/"]["merge"].append(splitski)
			#else:
			portage.db[splitski[1]]["merge"].append(splitski)	
			mygraph.delnode(mycurkey)
		for x in dolist:
			for y in portage.db[x]["merge"]:
				retlist.append(y)
		return retlist

	def syscreate(self,mylines=[]):
		for myline in mylines:	
			if "--update" in self.myopts:
			#or "--rebuild"==self.myaction:
				if not self.create(self.match(myline,mykey="update (likely old /var/db/pkg entry)")):
					return 0
			else:
				mycheck=portage.db[portage.root]["vartree"].depcheck(myline)
				if mycheck[0]==0:
					print "\n!!! Warning:",myline,"has an invalid depstring\n"
					continue
				if mycheck[1]==None:
					continue
				for x in mycheck[1]:
					if not self.create(self.match(myline,mykey="syscreate1")):
						return 0
		return 1
	
	def match(self,mydep,myroot=portage.root,mykey=None):
		# support mutual exclusive deps
		mydep2=mydep
		if mydep2[0]=="!":
			mydep2=mydep[1:]

		#if self.myaction=="--rebuild":
		#	myeb=portage.db[portage.root]["vartree"].dep_bestmatch(mydep2)
		#	if not portage.db[portage.root]["porttree"].exists_specific(myeb):
		#		self.outdatedpackages.append(myeb)
		#		return None
		#else:
		myeb=portage.db[portage.root]["porttree"].dep_bestmatch(mydep2)
		if not myeb:
			if not mykey:
				print "\n!!! Error: couldn't find match for",mydep
			else:
				print "\n!!! Error: couldn't find match for",mydep,"in",mykey
			print
			sys.exit(1)
			#return None

		if mydep[0]=="!":
			myk="blocks "+myroot+" "+mydep2
		else:
			if "--usepkg" in self.myopts:
				mypk=portage.db[portage.root]["bintree"].dep_bestmatch(mydep)
				if myeb==mypk:
					myk="binary "+portage.root+" "+mypk
				else:
					myk="ebuild "+myroot+" "+myeb
			else:
				myk="ebuild "+myroot+" "+myeb

		return myk	
	
	def display(self,mylist):
		for x in mylist:
			if x[0]=="blocks":
				addl=""+red("B")+"    "
				myspeckey=portage.db[x[1]]["vartree"].resolve_key(x[2])
				if myspeckey!=x[2]:
					print "["+x[0]+" "+addl+"]",red(x[2]+" ("+myspeckey+")")
				else:
					print "["+x[0]+" "+addl+"]",red(x[2])
			else:
				if portage.db[x[1]]["vartree"].exists_specific(x[2]):
					addl="  "+yellow("R")+"  "
				elif portage.db[x[1]]["vartree"].exists_specific_cat(x[2]):
					addl="   "+turquoise("U")+" "
				else:
					addl=" "+green("N")+"   "
				print "["+x[0]+" "+addl+"]",x[2],"to",x[1]

	def outdated(self):
		return self.outdatedpackages
				
	def merge(self,mylist):
		returnme=0
		#check for blocking dependencies
		for x in mylist:
			if x[0]=="blocks":
				print "\n!!! Error: the "+x[2]+" package conflicts with this package and both can't be installed on the same system together."
				sys.exit(1)

		#above line used by --fetchonly
		for x in mylist:
			myroot=x[1]
			print ">>> emerge",x[2],"to",x[1]
			#the last argument in the portage.doebuild() tells doebuild to *not* do dep checking
			#(emerge is already handling that)
			y=portage.db[myroot]["porttree"].getname(x[2])
			if x[0]=="ebuild":
				if "--fetchonly" in self.myopts:
					retval=portage.doebuild(y,"fetch",myroot,edebug)
					if retval:
						print
						print "!!! Fetch for",y,"failed, continuing..."
						print	
						returnme=1
				elif "--buildpkg" in self.myopts:
					#create pkg, then merge pkg
					retval=portage.doebuild(y,"clean",myroot,edebug)
					if retval:
						print "!!! emerge aborting on ",y,"."
						sys.exit(1)
					retval=portage.doebuild(y,"package",myroot,edebug)
					if retval:
						print "!!! emerge aborting on ",y,"."
						sys.exit(1)
					#dynamically update our database	
					portage.db[portage.root]["bintree"].inject(x[2])
					mytbz2=portage.db[portage.root]["bintree"].getname(x[2])
					retval=portage.pkgmerge(mytbz2,myroot)
					if retval==None:
						print "!!! emerge aborting on ",y,"."
						sys.exit(1)
				else:
					retval=portage.doebuild(y,"clean",myroot,edebug)
					if retval:
						print "!!! emerge aborting on ",y,"."
						sys.exit(1)
					retval=portage.doebuild(y,"merge",myroot,edebug)
					if retval:
						print "!!! emerge aborting on ",y,"."
						sys.exit(1)
					#dynamically update our database	
			elif x[0]=="binary":
				#merge the tbz2
				mytbz2=portage.db[portage.root]["bintree"].getname(x[2])
				retval=portage.pkgmerge(mytbz2,x[1])
				if retval==None:
					print "!!! emerge aborting on ",y,"."
					sys.exit(1)
				#need to check for errors
			portage.db[x[1]]["vartree"].inject(x[2])
			if (not "--fetchonly" in self.myopts) and (x[2] in favorites):
				mysplit=portage.catpkgsplit(x[2])
				myfavkey=mysplit[0]+"/"+mysplit[1]
				myfavs=portage.grabfile(myroot+"var/cache/edb/world")
				myfavdict=genericdict(myfavs)
				mysysdict=genericdict(syslist)
				#don't record if already in system profile or already recorded
				if (not mysysdict.has_key(myfavkey)) and (not myfavdict.has_key(myfavkey)):
					#we don't have a favorites entry for this package yet; add one
					myfavdict[myfavkey]=myfavkey
					print
					print ">>> Recording",myfavkey,"in \"world\" favorites file..."
					print
					portage.writedict(myfavdict,myroot+"var/cache/edb/world",writekey=0)
			if "--autoclean" in self.myopts:
				retval=portage.doebuild(y,"clean",myroot,edebug)
				if retval:
					print "!!! emerge aborting on ",y,"."
					sys.exit(1)
		#my doing an exit this way, --fetchonly can continue to try to
		#fetch everything even if a particular download fails.
		if "--fetchonly" in self.myopts:
			if returnme:
				print "\n\n!!! Some fetch errors were encountered.  Please see above for details.\n\n"
				sys.exit(returnme)
			else:
				sys.exit(0)

def unmerge(unmerge_action, unmerge_files):
	candidate_catpkgs=[]
	global_unmerge=0
	
	if not unmerge_files or "world" in unmerge_files or "system" in unmerge_files:
		if "unmerge"==unmerge_action:
			print
			print bold("emerge unmerge")+" can only be used with specific package names, not with "+bold("world")+" or"
			print bold("system")+" targets."
			print
			return 0
		else:
			global_unmerge=1
	
	localtree=portage.db[portage.root]["vartree"]
	# process all arguments and add all valid db entries to candidate_catpkgs
	if global_unmerge:
		if not unmerge_files or "world" in unmerge_files:
			candidate_catpkgs.extend(localtree.getallnodes())	
		elif "system" in unmerge_files:
			candidate_catpkgs.extend(getlist("system"))
	else:
		#we've got command-line arguments
		if not unmerge_files:
			print "\nNo packages to unmerge have been provided.\n"
			return 0
		for x in unmerge_files:
			arg_parts=x.split('/')
			if arg_parts[-1][-7:]!=".ebuild":
				#possible cat/pkg or dep; treat as such
				candidate_catpkgs.append(x)
			elif unmerge_action in ["prune","clean"]:
				print "\n!!! Prune and clean do not accept individual ebuilds as arguments;\n    skipping.\n"
				continue
			else:
				# it appears that the user is specifying an installed ebuild and we're in "unmerge" mode, so it's
				# ok.
				if not os.path.exists(x):
					print "\n!!! The path '"+x+"' doesn't exist.\n"
					return 0
				absx=os.path.abspath(x)
				spabsx=absx.split("/")
				if absx[:12]!="/var/db/pkg/" or len(spabsx)!=7:
					print spabsx
					print absx
					print "\n!!!",x,"is not inside /var/db/pkg; aborting.\n"
					return 0
				candidate_catpkgs.append("="+spabsx[4]+"/"+spabsx[5])

	if "--pretend" in myopts:
		print"\n>>> These are the packages that I would unmerge:"
	
	pkgmap={}
	numselected=0
	for x in candidate_catpkgs:
		#cycle through all our candidate deps and determine what will and will not get unmerged
		mymatch=localtree.dep_match(x)
		if not mymatch and x[0] not in "<>=~":
			#add a "=" if missing
			mymatch=localtree.dep_match("="+x)
		if not mymatch:
			print "\n!!! Couldn't find match for",white(x)
			continue
		if not pkgmap.has_key(x):
			pkgmap[x]={"protected":[], "selected":[], "omitted":[] }
		if unmerge_action=="unmerge":
				pkgmap[x]["selected"].extend(mymatch)
				numselected=numselected+len(mymatch)
		else:
			#unmerge_action in ["prune", clean"]
			slotmap={}
			for mypkg in mymatch:
				if unmerge_action=="clean":
					myslot=localtree.getslot(mypkg)
				else:
					#since we're pruning, we don't care about slots and put all the pkgs in together
					myslot=0
				if not slotmap.has_key(myslot):
					slotmap[myslot]={}
				slotmap[myslot][localtree.gettimeval(mypkg)]=mypkg
			for myslot in slotmap.keys():
				counterkeys=slotmap[myslot].keys()
				counterkeys.sort()
				if not counterkeys:
					continue
				counterkeys.sort()
				pkgmap[x]["protected"].append(slotmap[myslot][counterkeys[-1]])
				del counterkeys[-1]
				#be pretty and get them in order of merge:
			for ckey in counterkeys:
					pkgmap[x]["selected"].append(slotmap[myslot][ckey])
					numselected=numselected+1
				#ok, now the last-merged package is protected, and the rest are selected
		pkgmap[x]["omitted"].extend(localtree.dep_nomatch(x))
		
	if global_unmerge and not numselected:
		print "\n>>> No outdated packages were found on your system.\n"
		return 0
	
	for x in pkgmap.keys():
		if global_unmerge and not pkgmap[x]["selected"]:
			#avoid cluttering the preview printout with stuff that isn't getting unmerged
			continue
		print "\n "+white(x)
		for mytype in ["selected","protected","omitted"]:
			print string.rjust(mytype,12)+":",
			if pkgmap[x][mytype]:
				for mypkg in pkgmap[x][mytype]:
					mysplit=portage.catpkgsplit(mypkg)
					if mysplit[3]=="r0":
						myversion=mysplit[2]
					else:
						myversion=mysplit[2]+"-"+mysplit[3]
					if mytype=="selected":
						print red(myversion),
					else:
						print green(myversion),
			else:
					print "none",
			print
	
	if not numselected:
		print "\n>>>",unmerge_action+": No packages selected for removal.\n"
		return 0

	print "\n>>> Packages in",red("red"),"are slated for removal."
	print ">>> Packages in",green("green"),"will not be removed.\n"
	
	if "--pretend" in myopts:
		#we're done... return
		return 0
	#the real unmerging begins, after a short delay....
	
	if portage.settings["CLEAN_DELAY"]:
		secs=string.atoi(portage.settings["CLEAN_DELAY"])
	else:
		secs=5
	if secs > 0:
		print ">>> Waiting",secs,"seconds before starting unmerge."
		print ">>> (Control-C to abort)...\n>>> Unmerging in: ",
		while secs > 0:
			sys.stdout.write(red(str(secs)+" "))	
			sys.stdout.flush()
			time.sleep(1)
			secs=secs-1
		print secs
	for x in pkgmap.keys():
		for y in pkgmap[x]["selected"]:
			print ">>> Unmerging "+y+"..."
			mysplit=string.split(y,"/")
			#unmerge...
			retval=portage.unmerge(mysplit[0],mysplit[1],portage.root)
			#remove db entry from our "live" tree
			localtree.zap(y)
	if not numselected:
		return 0
	else:
		return 1

def post_emerge(retval=0):
	auxpat=re.compile('^([^-]*)(-\d+)?\.info(-\d+)?(\.gz)?')	
	global myopts
	print
	if "--pretend" in myopts:
		sys.exit(retval)
	root=portage.root
	if os.path.isdir(root+"usr/share/info") and os.path.exists("/usr/bin/install-info"):
		print " "+green("*")+" Regenerating GNU info directory index..."
		try:
			os.rename(root+"usr/share/info/dir",root+"usr/share/info/dir.old")
		except:
			pass
		icount=0
		badcount=0
		for x in os.listdir(root+"usr/share/info"):
			aux=auxpat.search(x)
			if not aux:
				continue
			auxgroups=aux.groups()	
			if not (auxgroups[1] or auxgroups[2]):
				myso=commands.getstatusoutput("/usr/bin/install-info --dir-file="+root+"usr/share/info/dir "+root+"usr/share/info/"+x)[1]
				if myso!="":
					badcount=badcount+1
					if "--verbose" in myopts:
						print myso
				icount=icount+1
		if badcount:
			if "--verbose" not in myopts:
				print " "+yellow("*")+" Processed",icount,"info files:",badcount,"errors; type "+green("emerge --verbose")+" to view errors."
			else:
				print " "+yellow("*")+" Processed",icount,"info files;",badcount,"errors."

		else:
			print " "+green("*")+" Processed",icount,"info files."
	if portage.settings["CONFIG_PROTECT"]:
		#number of directories with some protect files in them
		procount=0
		for x in string.split(portage.settings["CONFIG_PROTECT"]):
			if os.path.isdir(x):
				a=commands.getstatusoutput("cd "+x+"; find -iname '._cfg????_*'")
				if a[0]!=0:
					print " "+red("*")+" error scanning",x
				else:
					files=string.split(a[1])
					if files:
						procount=procount+1
						print " "+yellow("* IMPORTANT:")+"",len(files),"config files in",x,"need updating."
		if procount:
			print " "+yellow("*")+" Type "+green("emerge --help config")+" to learn how to update config files."
		print
	sys.exit(retval)

# general options that should be taken into account before any action
if "noclean" not in portage.features:
	if not "--autoclean" in myopts:
		myopts.append("--autoclean")
if "--debug" in myopts:
	edebug=1

if myaction in ["sync","rsync"]:
	rclean=0
	myportdir=portage.settings["PORTDIR"]
	if myportdir[-1]=="/":
		myportdir=myportdir[:-1]
	if not os.path.exists(myportdir):
		print ">>>",myportdir,"not found, creating it."
		os.makedirs(myportdir,0755)	
	if "--clean" in myopts:
		#we'll --delete files when we rsync
		rclean=1
	syncuri=portage.settings["SYNC"]
	os.umask(022)
	if syncuri[:8]=="rsync://":
		if not os.path.exists("/usr/bin/rsync"):
			print "!!! /usr/bin/rsync does not exist, so rsync support is disabled."
			print "!!! Type \"emerge net-misc/cvs\" to enable rsync support."
			sys.exit(1)
		mycommand="/usr/bin/rsync -rlptDvz --stats --progress "
		if rclean:
			mycommand=mycommand+"--delete --exclude='distfiles/*' --exclude='packages/*' "
		mycommand=mycommand+syncuri+"/* "+myportdir
		#rsync://cvs.gentoo.org/gentoo-x86-portage/* "+myportdir
		print ">>> starting rsync with "+syncuri+"..."
	#protect users that did not set a default umask
		sys.exit(portage.spawn(mycommand,free=1))	
	elif syncuri[:6]=="cvs://":
		if not os.path.exists("/usr/bin/cvs"):
			print "!!! /usr/bin/cvs does not exist, so rsync support is disabled."
			print "!!! Type \"emerge dev-util/cvs\" to enable CVS support."
			sys.exit(1)
		cvsroot=syncuri[6:]
		cvsdir=os.path.dirname(myportdir)
		if not os.path.exists(myportdir+"/CVS"):
			#initial checkout
			print ">>> starting initial cvs checkout with "+syncuri+"..."
			if not portage.spawn("cd "+cvsdir+"; cvs -d "+cvsroot+" login",free=1):
				print "!!! cvs login error; exiting."
				sys.exit(1)
			if os.path.exists(cvsdir+"/gentoo-x86"):
				print "!!! existing",cvsdir+"/gentoo-x86 directory; exiting."
				sys.exit(1)
			if not portage.spawn("cd "+cvsdir+"; cvs -d "+cvsroot+" co gentoo-x86",free=1):
				print "!!! cvs checkout error; exiting."
				sys.exit(1)
			if cvsdir!=myportdir:
				portage.movefile(cvsdir,portage.settings["PORTDIR"])
			sys.exit(0)
		else:
			#cvs update
			print ">>> starting cvs update with "+syncuri+"..."
			sys.exit(portage.spawn("cd "+myportdir+"; cvs -q update -dP",free=1)) 
	else:
		print "!!! rsync setting: ",syncuri,"not recognized; exiting."
		sys.exit(1)

elif "--version" in myopts:
		print "Portage " + portage.VERSION
		sys.exit(0)
# HELP action
elif "--help" in myopts:
	if not myaction:
		print
		print bold("Usage: ")+turquoise("emerge")+" [ "+green("options")+" ] [ "+green("action")+" ] [ "+turquoise("ebuildfile")+" | "+turquoise("tbz2file")+" | "+turquoise("dependency")+" ] ..."
		print "       "+turquoise("emerge")+" [ "+green("options")+" ] [ "+green("action")+" ] "+turquoise("system")
		print "       "+turquoise("emerge")+" [ "+green("--clean")+" "+green("-c")+" ] "+turquoise("sync")+" | "+turquoise("rsync")
		print "       "+turquoise("emerge")+" "+green("--help")+" "" "+green("-h")+" [ "+turquoise("rsync")+" | "+turquoise("system")+" | "+turquoise("config")+" ] "
		print
		print turquoise("Help (this screen):")
		print "       "+green("--help")+" ("+green("-h")+" short option)"
		print "              Displays this help; an additional argument (see above) will tell"
		print "              emerge to display detailed help."
		print
		print turquoise("Actions:")
		print "       "+green("clean")+" ("+green("-c")+" short option)"
		print "              Cleans the system by removing outdated packages which will not"
		print "              remove functionalities or prevent your system from working."
		print "              The arguments can be in several different formats :"
		print "              * world "
		print "              * system "
		print "              * /var/db/pkg/category/package-version, or"
		print "              * 'dependency specification' (in single quotes is best.)"
		print "              Here are a few examples of the dependency specification format:"
		print "              "+bold("binutils")+" matches"
		print "                  binutils-2.11.90.0.7 and binutils-2.11.92.0.12.3-r1"
		print "              "+bold(">binutils-2.11.90.0.7")+" matches"
		print "                  binutils-2.11.92.0.12.3-r1"
		print "              "+bold("sys-devel/binutils")+" matches"
		print "                  binutils-2.11.90.0.7 and binutils-2.11.92.0.12.3-r1"
		print "              "+bold("sys-devel/binutils-2.11.90.0.7")+" matches"
		print "                  binutils-2.11.90.0.7"
		print "              "+bold(">sys-devel/binutils-2.11.90.0.7")+" matches"
		print "                  binutils-2.11.92.0.12.3-r1"
		print "              "+bold(">=sys-devel/binutils-2.11.90.0.7")+" matches"
		print "                  binutils-2.11.90.0.7 and binutils-2.11.92.0.12.3-r1"
		print "              "+bold("<sys-devel/binutils-2.11.92.0.12.3-r1")+" matches"
		print "                  binutils-2.11.90.0.7"
		print "              "+bold("<=sys-devel/binutils-2.11.92.0.12.3-r1")+" matches"
		print "                  binutils-2.11.90.0.7 and binutils-2.11.92.0.12.3-r1"
		print
		print "       "+green("unmerge")+" ("+green("-C")+" short option)"
		print "              "+turquoise("WARNING: This action can remove important packages!")
		print "              Removes all matching packages without checking for outdated."
		print "              versions. This thus effectively removes a package "+bold("completely")+" from"
		print "              your system. Specify arguments using the dependency specification"
		print "              format described in the "+bold("clean")+" action above."
		print
		print "       "+green("prune")+" ("+green("-P")+" short option)"
		print "              "+turquoise("WARNING: This action can remove important packages!")
		print "              Removes all older versions of a package from your system."
		print "              This action doesn't always verify the possible binary"
		print "              incompatibility between versions and can thus remove essential"
		print "              dependencies from your system."
		print "              The argument format is the same as for the "+bold("clean")+" action."
		print
		print "       "+green("search")+" ("+green("-s")+" short option)"
		print "              searches for matches of the supplied string in the current local"
		print "              portage tree. The search string is a regular expression."
		print "              A few examples: "
		print "              "+bold("emerge search '^kde'")
		print "                  list all packages starting with kde"
		print "              "+bold("emerge search 'gcc$'")
		print "                  list all packages ending with gcc"
		print "              "+bold("emerge search ''")+" or"
		print "              "+bold("emerge search '.*'")
		print "                  list all available packages "
		print
		print "       "+green("inject")+" ("+green("-i")+" short option)"
		print "              Add a stub entry for a package so that Portage thinks that it's"
		print "              installed when it really isn't.  Handy if you roll your own"
		print "              packages.  Example: "
		print "              "+bold("emerge inject gentoo-sources-2.4.19")
		print
		print turquoise("Options:")
		print "       "+green("--autoclean")+" ("+green("-a")+" short option)"
		print "              emerge normally cleans out the package-specific temporary"
		print "              build directory before it starts the building a package.  With"
		print "              --autoclean, it will also clean the directory *after* the"
		print "              build completes.  This option is automatically enabled for"
		print "              normal users, but maintainers can use this option to enable"
		print "              autocleaning."
		print
		print "       "+green("--buildpkg")+" ("+green("-b")+" short option)"
		print "              tell emerge to build binary packages for all ebuilds processed"
		print "              (in addition to actually merging the packages.  Useful for"
		print "              maintainers or if you administrate multiple Gentoo Linux"
		print "              systems (build once, emerge tbz2s everywhere)."
		print
		print "       "+green("--debug")+" ("+green("-d")+" short option)"
		print "              Tell emerge to run the ebuild command in --debug mode. In this"
		print "              mode, the bash build environment will run with the -x option,"
		print "              causing it to output verbose debug information print to stdout."
		print "              --debug is great for finding bash syntax errors."
		print
		print "       "+green("--emptytree")+" ("+green("-e")+" short option)"
		print "              Virtually tweaks the tree of installed packages to only contain"
		print "              glibc, this is great to use together with --pretend. This makes"
		print "              it possible for developers to get a complete overview of the"
		print "              complete dependency tree of a certain package."
		print
		print "       "+green("--fetchonly")+" ("+green("-f")+" short option)"
		print "              Instead of doing any package building, just perform fetches for"
		print "              all packages (main package as well as all dependencies.)"
		print
		print "       "+green("--nodeps")
		print "              Merge specified packages, but don't merge any dependencies."
		print "              Note that the build may fail if deps aren't satisfied."
		print 
		print "       "+green("--noreplace")+" ("+green("-n")+" short option)"
		print "              Skip the packages specified on the command-line that have"
		print "              already been installed.  Without this option, any packages,"
		print "              ebuilds, or deps you specify on on the command-line *will* cause"
		print "              Portage to remerge the package, even if it is already installed."
		print "              Note that Portage won't remerge dependencies by default."
		print
		print "       "+green("--oneshot")
		print "              Emerge as normal, but don't add packages to the world profile for"
		print "              later updating."
		print
		print
		print "       "+green("--onlydeps")+" ("+green("-o")+" short option)"
		print "              Only merge (or pretend to merge) the dependencies of the"
		print "              specified packages, not the packages themselves."
		print
		print "       "+green("--pretend")+" ("+green("-p")+" short option)"
		print "              instead of actually performing the merge, simply display what"
		print "              ebuilds and tbz2s *would* have been installed if --pretend"
		print "              weren't used.  Using --pretend is strongly recommended before"
		print "              installing an unfamiliar package.  In the printout, N = new,"
		print "              U = upgrading, R = replacing, B = blocked by an already installed"
		print "              package."
		print
		print "       "+green("--update")+" ("+green("-u")+" short option)"
		print "              Updates packages to the most recent version available."
		print 
		print "       "+green("--usepkg")+" ("+green("-k")+" short option)"
		print "              tell emerge to use binary packages (from $PKGDIR) if they are"
		print "              available, thus possibly avoiding some time-consuming compiles."
		print "              This option is useful for CD installs; you can export"
		print "              PKGDIR=/mnt/cdrom/packages and then use this option to have"
		print "              emerge \"pull\" binary packages from the CD in order to satisfy" 
		print "              dependencies."
		print
		print "       "+green("--verbose")+" ("+green("-v")+" short option)"
		print "              Tell emerge to run in verbose mode.  Currently, this causes"
		print "              emerge to print out GNU info errors, if any."
	elif myaction in ["rsync","sync"]:
		print
		print bold("Usage: ")+turquoise("emerge")+" [ "+green("--clean")+" "+green("-c")+" ] "+turquoise("sync")
		print
		print "       \"emerge sync\" tells emerge to update the Portage tree as specified in"
		print "       The SYNC variable found in /etc/make.conf.  By default, SYNC instructs"
		print "       emerge to perform an rsync-style update with cvs.gentoo.org.  Available"
		print "       sync methods are rsync and anoncvs.  To use anoncvs rather than rsync,"
		print "       put 'SYNC=\"cvs://:pserver:cvs.gentoo.org:/home/cvsroot\" in your"
		print "       /etc/make.conf.  If you haven't used anoncvs before, you'll be prompted"
		print "       for a password, which for cvs.gentoo.org is empty (just hit enter.)"
		print "       "+turquoise("NOTE:")+" if using rsync, adding a --clean will tell emerge to"
		print "       remove any files in your Portage tree that aren't in our main repository."
		print
	elif myaction=="system":
		print
		print bold("Usage: ")+turquoise("emerge")+" [ "+green("options")+" ] "+turquoise("system")
		print
		print "       \"emerge system\" is the Portage system update command.  When run, it"
		print "       will scan the etc/make.profile/packages file and determine what"
		print "       packages need to be installed so that your system meets the minimum"
		print "       requirements of your current system profile.  Note that this doesn't"
		print "       necessarily bring your system up-to-date at all; instead, it just"
		print "       ensures that you have no missing parts.  For example, if your system"
		print "       profile specifies that you should have sys-apps/iptables installed"
		print "       and you don't, then \"emerge system\" will install it (the most"
		print "       recent version that matches the profile spec) for you.  It's always a"
		print "       good idea to do an \"emerge --pretend system\" before an \"emerge"
		print "       system\", just so you know what emerge is planning to do."
		print
	elif myaction=="config":
		outstuff=green("Config file management support (preliminary)")+"""

Portage has a special feature called "config file protection".  The purpose of
this feature is to prevent new package installs from clobbering existig
configuration files.  By default, config file protection is turned on for /etc
and the KDE configuration dirs; more may be added in the future.

When Portage installs a file into a protected directory tree like /etc, any
existing files will not be overwritten.  If a file of the same name already
exists, Portage will change the name of the to-be- installed file from 'foo' to
'._cfg0000_foo'.  If '._cfg0000_foo' already exists, this name becomes
'._cfg0001_foo', etc.  In this way, existing files are not overwritten,
allowing the administrator to manually merge the new config files and avoid any
unexpected changes.

In addition to protecting overwritten files, Portage will not delete any files
from a protected directory when a package is unmerged.  While this may be a
little bit untidy, it does prevent potentially valuable config files from being
deleted, which is of paramount importance.

Protected directories are set using the CONFIG_PROTECT variable, normally
defined in /etc/make.globals.  Directory exceptions to the CONFIG_PROTECTed
directories can be specified using the CONFIG_PROTECT_MASK variable.  To find
files that need to be updated in /etc, type:

# find /etc -iname '._cfg????_*'

You can disable this feature by setting CONFIG_PROTECT="" in /etc/make.conf.
Then, Portage will mercilessly auto-update your config files.  Alternatively,
you can leave Config File Protection on but tell Portage that it can overwrite
files in certain specific /etc subdirectories.  For example, if you wanted
Portage to automatically update your rc scripts and your wget configuration,
but didn't want any other changes made without your explicit approval, you'd
add this to /etc/make.conf:

CONFIG_PROTECT_MASK="/etc/wget /etc/rc.d"

"""
		print outstuff
elif "config"==myaction:
	print
	print "Currently, \'config\' is a --help option only."
	print
# SEARCH action
elif "search"==myaction:
	if not myfiles:
		print
		print "No search terms provided."
		print
	else:
		searchinstance = search()
		for mysearch in myfiles:
			searchinstance.setKey(mysearch)
			searchinstance.execute()
			searchinstance.output()
elif "inject"==myaction:
	for x in myfiles:
		if not portage.catpkgsplit(x):
			print "!!!",x,"is not a specific cat/pkg-version, skipping..."
			continue
		if portage.db["/"]["vartree"].exists_specific(x):
			print "!!! Not injecting",x+"; Package already exists."
		else:
			os.makedirs("/var/db/pkg/"+x)
			print ">>> Injected",x+"."
elif "unmerge"==myaction or "prune"==myaction or "clean"==myaction:
	if 1==unmerge(myaction, myfiles):
		post_emerge()
	
# "update", "system", or just process files:
else:
	if "--pretend" in myopts:
		print
		print "These are the packages that I would merge, in order."
		print
	mydepgraph=depgraph(myaction,myopts)
	favorites=[]
	syslist=getlist("system")
	if myaction=="system":
		print "Calculating system dependencies  ",
		if not mydepgraph.syscreate(syslist):
			sys.exit(1)
		print "\b\b ...done!"
	elif myaction=="world":
		print "Calculating world dependencies  ",
		if not mydepgraph.syscreate(getworldlist()):
			sys.exit(1)
		print "\b\b ...done!"
	else:
		if not myfiles:
			post_emerge()
			#we don't have any files to process; skip this step and exit
		print "Calculating dependencies  ",
		for mypkg in myfiles:
			if mypkg[-5:]==".tbz2":
				mytype="binary"
				mytbz2=xpak.tbz2(mypkg)
				mykey=mytbz2.getelements("CATEGORY")[0]+"/"+os.path.basename(mypkg)[:-5]
			elif mypkg[-7:]==".ebuild":
				mytype="ebuild"
				mykey=os.path.basename(os.path.abspath(mypkg+"/../.."))+"/"+os.path.basename(mypkg)[:-7]
			else:
				mykey=""
				if "--usepkg" in myopts:
					mykey=portage.db[portage.root]["bintree"].dep_bestmatch(mypkg)
					mytype="binary"
				if not mykey:
					mykey=portage.db[portage.root]["porttree"].dep_bestmatch(mypkg)
					mytype="ebuild"
					if not mykey:
						print "!!! Couldn't find match for",mypkg+"; aborting."
						sys.exit(1)
			#	else:
			#		print "!!! Error:",x,"is neither an ebuild nor a .tbz2 package."
			#		sys.exit(1)
			if not "--oneshot" in myopts:
				favorites.append(mykey)
			if not mydepgraph.create(mytype+" "+portage.root+" "+mykey,None,"--onlydeps" not in myopts):
				sys.exit(1)
		print "\b\b ...done!"
	if "--pretend" in myopts:
		mydepgraph.display(mydepgraph.altlist())
	else:
		mydepgraph.merge(mydepgraph.altlist())
		if portage.settings["AUTOCLEAN"] and "yes"==portage.settings["AUTOCLEAN"]:
			print ">>> Auto-cleaning packages ..."
			unmerge("clean", ["world"])
	post_emerge()

