#!/usr/bin/python
# 
# Paul Nasrat <pnasrat@redhat.com>
# Copyright 2005 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os.path
import glob
import rpm
import rpmUtils
import string
import sys
import yum

import logging
logger = logging.getLogger("anaconda")
handler = logging.StreamHandler()
handler.setLevel(logging.ERROR)
logger.addHandler(handler)

sys.path.append("/usr/lib/anaconda")

from optparse import OptionParser
from repomd.packageSack import PackageSack
from repomd.packageObject import PackageObject
from yuminstall import YumSorter
import iutil

class PackageOrderer(YumSorter):

    def __init__(self, arch=None):
        YumSorter.__init__(self)
        self.arch = arch
        self._installed = PackageSack()

    def setup(self, fn="/etc/yum.conf", root="/", excludes=[]):
        self.doConfigSetup(fn, root)
        self.conf.cache = 0
#         if hasattr(self.repos, 'sqlite'):
#             self.repos.sqlite = False
#             self.repos._selectSackType()
        exclude = self.conf.exclude
        exclude.extend(excludes)
        self.conf.exclude = exclude
        cachedir = yum.misc.getCacheDir()
        self.repos.setCacheDir(cachedir) 
        self.repos.setCache(0) 
        self.doRepoSetup()

        self.doSackSetup(rpmUtils.arch.getArchList(self.arch))
        self.doTsSetup()
        self.doGroupSetup()
        self.repos.populateSack(with='filelists')

    def errorlog(self, value, msg):
        pass

    def filelog(self, value, msg):
        pass

    def log(self, value, msg):
        pass

    def getDownloadPkgs(self):
        pass

#XXX: sigh
processed = {}
def processTransaction(ds):
#    ds.tsInfo.makelists()
#    print len(ds.tsInfo.installed)
#    import pdb; pdb.set_trace()
    for pkgtup in ds.tsInfo.sort():
        fname = ds.tsInfo.pkgdict[pkgtup][0].po.returnSimple('relativepath')
        fpattern = "%s/%s*" % (toppath, fname.rsplit('.', 2)[0])
        printMatchingPkgs(fpattern)

def printMatchingPkgs(fpattern):
    global processed

    matches = glob.glob(fpattern)

    for match in matches:
        mname = os.path.basename(match)
        if processed.has_key(mname): continue
        processed[mname] = True
        print mname

def addGroups(ds, groupLst):
    ds.initActionTs()
    map(ds.selectGroup, groupLst)
    ds.resolveDeps()
    processTransaction(ds)

def createConfig(toppath):
    yumconfstr = """
[main]
distroverpkg=redhat-release
gpgcheck=0
reposdir=/dev/null
exclude=*debuginfo*

[anaconda]
name=Anaconda
baseurl=file://%s
enabled=1
""" % (toppath)
    
    try:
        (fd, path) = tempfile.mkstemp("", "yum-conf-", toppath)
    except (OSError, IOError), e:
        print >> sys.stderr, "Error writing to %s" % (toppath,)
        sys.exit(1)
    os.write(fd, yumconfstr)
    os.close(fd)
    return path

def usage():
    print >> sys.stderr, "pkgorder <toppath> <arch> <productpath>"
    print >> sys.stderr, "<arch>: use rpm architecture for tree, eg i686"

if __name__ == "__main__":
    import tempfile
    parser = OptionParser()
    parser.add_option("--debug", action="store_true", dest="debug", default=False)
    parser.add_option("--file", action="store", dest="file")
    parser.add_option("--product", action="store", dest="productPath", )
    parser.add_option("--exclude", action="append", dest="excludeList",
                      default=[])

    (options, args) = parser.parse_args()
     
    if len(args) != 3:
	usage()
        sys.exit(1)

    (toppath, arch, product) = args
    config = createConfig(toppath)

    # Boo.
    if arch == "i386":
        arch = "i686"

    for pattern in ["kernel-[0-9]*", "kernel-smp-[0-9]*",
                    "kernel-xen*"]:
        printMatchingPkgs("%s/%s/RPMS/%s" % (toppath, product, pattern))

    testpath = "/tmp/pkgorder-Momonga"
    os.system("mkdir -p %s/var/lib/rpm" %(testpath,))
    
    ds = PackageOrderer(arch=arch)
    ds.setup(fn=config, excludes=options.excludeList, root = testpath)

    addGroups(ds, ["Core", "Base", "Text-based Internet"])

    addGroups(ds, ["X Window System", "Dialup Networking Support",
                   "Graphical Internet", "Editors", 
                   "Graphics", "GNOME Desktop Environment", "Sound and Video",
                   "Printing Support", "Dialup Networking Support"])

    addGroups(ds, ["Office/Productivity", "Engineering and Scientific",
                   "Authoring and Publishing", "Games and Entertainment"])

    addGroups(ds, ["Web Server", "FTP Server", "MySQL Database",
                   "Server Configuration Tools", "DNS Name Server",
                   "Windows File Server", "Administration Tools"])

    addGroups(ds, ["KDE (K Desktop Environment)", "Development Tools",
                   "GNOME Software Development",
                   "KDE Software Development",
                   "PostgreSQL Database", "Mail Server",
                   "Legacy Network Server"])

    addGroups(ds, ["News Server", "Legacy Software Development"])

    #Everthing else but kernels - don't depsolve
    for po in ds.pkgSack.returnPackages():
        if po.pkgtup not in ds._installed.returnPackages():
            if po.name.find("kernel") == -1:
                member = ds.tsInfo.addInstall(po)

    processTransaction(ds)
    os.unlink(config)
    iutil.rmrf(testpath)
