#!/usr/bin/python -O

# ojo esto y --version solo puesto para que pase make distcheck
# ver si no se instala como libreria

#sys.path = ["/usr/lib/portage/pym"]+sys.path
# ideas tomadas de 1) gentoo, 2) emerde, 3) de un script que alguien me paso en una lista hace mucho, no recuerdo su nombre
# xpak.py de gentoo, ultima version /usr/lib64/portage/pym/portage/xpak.py
#2010, Diego Saravia, diego.saravia@gmail.com, en lo que me toque AGPLv3+

        # poner opcion al upak para anhadir sobre si mismo, salida sobre salida estandar,de info  o paquete

import sys, os, shutil, xpak



if len(sys.argv)>1:
 order=sys.argv[1]
 if order=="--version":
   print "0.1"
   sys.exit(0) 
 elif order=="--help":
  print " Ututo Pack"
  print ""
  print "upack --ORDER SOURCE RESULT INFO-DIRECTORY"
  print ""
  print "Pack, reads infodir and package.tar.bz2, creates package.tbz2"
  print "upack --pack package.tar.bz2 package.tbz2 infodir"
  print ""
  print "Unpack, create infodir and package.tar.bz2, reads package.tbz2"
  print "upack --unpack package.tbz2 package.tar.bz2 infodir"
  sys.exit(0) 
else:
  print "upak: Expecting one order (ex: --pack) and 3 other arguments, unless order is --help or --version"
  sys.exit(1) 

if len(sys.argv)!=5 :
   print "upak: expecting one order (ex --pack) and 3 other arguments, unless order is --help or --version"
   sys.exit(1) 


read=sys.argv[2]   
write=sys.argv[3]   
dirinfo=sys.argv[4]

if order=="--pack":
    shutil.copy(read,write)
    xpak.tbz2(write).recompose_mem(xpak.xpak(dirinfo))
elif order=="--unpack":
    if not os.path.isdir(dirinfo):   #os.path.exists  #os.makedirs
       os.mkdir(dirinfo)
    xpak.tbz2(read).unpackinfo(dirinfo)
    # no vi como crear un tbz2 sin la ultima parte, pero en fin, el tar lo usa igual.
    shutil.copy(read,write)
else:
    print "The first argument must be: --pack, --unpack, --help or --version."




def cleanup_pkgmerge(mypkg,origdir):
	global settings
	shutil.rmtree(settings["PORTAGE_TMPDIR"]+"/binpkgs/"+mypkg)
	if os.path.exists(settings["PORTAGE_TMPDIR"]+"/portage/"+mypkg+"/temp/environment"):
		os.unlink(settings["PORTAGE_TMPDIR"]+"/portage/"+mypkg+"/temp/environment")
	os.chdir(origdir)

def pkgmerge(mytbz2, myroot, mysettings, mydbapi=None, vartree=None, prev_mtimes=None):
	"""will merge a .tbz2 file, returning a list of runtime dependencies
		that must be satisfied, or None if there was a merge error.	This
		code assumes the package exists."""
	global db
	if mydbapi is None:
		mydbapi = db[myroot]["bintree"].dbapi
	if vartree is None:
		vartree = db[myroot]["vartree"]
	if mytbz2[-5:]!=".tbz2":
		print "!!! Not a .tbz2 file"
		return None
	mypkg=os.path.basename(mytbz2)[:-5]
	xptbz2=xpak.tbz2(mytbz2)
	pkginfo={}
	mycat=xptbz2.getfile("CATEGORY")
	if not mycat:
		print "!!! CATEGORY info missing from info chunk, aborting..."
		return None
	mycat=mycat.strip()
	mycatpkg=mycat+"/"+mypkg
	tmploc=mysettings["PORTAGE_TMPDIR"]+"/binpkgs/"
	pkgloc=tmploc+"/"+mypkg+"/bin/"
	infloc=tmploc+"/"+mypkg+"/inf/"
	myebuild=tmploc+"/"+mypkg+"/inf/"+os.path.basename(mytbz2)[:-4]+"ebuild"
	if os.path.exists(tmploc+"/"+mypkg):
		shutil.rmtree(tmploc+"/"+mypkg,1)
	os.makedirs(pkgloc)
	os.makedirs(infloc)
	writemsg_stdout(">>> Extracting info\n")
	xptbz2.unpackinfo(infloc)
	# run pkg_setup early, so we can bail out early
	# (before extracting binaries) if there's a problem
	origdir=getcwd()
	os.chdir(pkgloc)

	mysettings.configdict["pkg"]["CATEGORY"] = mycat;
	# Eventually we'd like to pass in the saved ebuild env here.
	# Do cleanup=1 to ensure that there is no cruft prior to the setup phase.
	a = doebuild(myebuild, "setup", myroot, mysettings, tree="bintree",
		cleanup=1, mydbapi=mydbapi, vartree=vartree)
	writemsg_stdout(">>> Extracting %s\n" % mypkg)
	notok=spawn("bzip2 -dqc -- '"+mytbz2+"' | tar xpf -",mysettings,free=1)
	if notok:
		print "!!! Error Extracting",mytbz2
		cleanup_pkgmerge(mypkg,origdir)
		return None

	# the merge takes care of pre/postinst and old instance
	# auto-unmerge, virtual/provides updates, etc.
	mysettings.load_infodir(infloc)
	mylink=dblink(mycat,mypkg,myroot,mysettings,treetype="bintree")
	mylink.merge(pkgloc, infloc, myroot, myebuild, cleanup=1, prev_mtimes=prev_mtimes)

	if not os.path.exists(infloc+"/RDEPEND"):
		returnme=""
	else:
		#get runtime dependencies
		a=open(infloc+"/RDEPEND","r")
		returnme=string.join(string.split(a.read())," ")
		a.close()
	cleanup_pkgmerge(mypkg,origdir)
	return returnme


