#!/usr/bin/python


import os
import sys
import time
import glob
import string
import fnmatch

import rpm

sys.path.append("/usr/share/rhn/")
from up2date_client import rpmSource
from up2date_client import rpmSourceUtils
from up2date_client import rhnChannel
from up2date_client import repoDirector
from up2date_client import config
from up2date_client import rpcServer
from up2date_client import rpmUtils
from up2date_client import up2dateUtils
from up2date_client import transaction

import genericRepo
import genericSolveDep

class CmdlineSolveDep(genericSolveDep.SolveByHeadersSolveDep):
    def __init__(self):
        genericSolveDep.SolveByHeadersSolveDep.__init__(self)
        self.type = "cmdline"


class CmdlineRepoSource(rpmSource.PackageSource):
    def __init__(self, proxyHost=None,
                 loginInfo=None, cacheObject=None):
        self.cfg = config.initUp2dateConfig()
        rpmSource.PackageSource.__init__(self, cacheObject = cacheObject)
        self.headerCache = cacheObject
        self.obsList = []

    def listPackages(self, channel,
                     sgCallback = None, progressCallback = None):

        # grab the list of filenames we set aside earlier in wrapper.py
        pkgs = rhnChannel.cmdline_pkgs

        # create a channel list...
        # do obsoletes stuff?
        # grab headers...

        
        # since were talking local file, and we are already
        # loading them up and poking at the headers, lets figure
        # out the obsoletes stuff now too while were at it
        self.obsList = []
        
        pkgList = []
        
        total = len(pkgs)
        count = 0
        for rpmpath in pkgs:
            # ignore if it its an inapproriate arch... warn here?
            bits = string.split(filename, ".")
            arch = bits[-2]
            if rpm.archscore(arch) == 0:
                print "%s is not of a valid arch" % rpmpath
                continue
            
            
            # might as well collect the filesize 
            hdrBuf = self.__getHeader(rpmpath)
            hdr = rpmUtils.readHeaderBlob(hdrBuf.unload())
            size = os.stat(rpmpath)[6]
            
            # you know... if we didnt care about epoch,
            # we could just skip reading the headers at all
            # at this point, cutting down the number of headers
            # we read by potentially a lot in beehive style trees
            epoch = hdr['epoch']
            if epoch == None:
                epoch = ""
            else:
                epoch = str(epoch)
            pkgList.append([hdr['name'], hdr['version'],
                            hdr['release'], epoch, hdr['arch'],
                            size, channel['label'], rpmpath])

            # populate any obsoletes info...
            for pkg in pkgList:
                rpmpath = pkg[7]
                hdrBuf = self.__getHeader(rpmpath)
                hdr = rpmUtils.readHeaderBlob(hdrBuf.unload())

            
                # look for header info
                if not hdr['obsoletes']:
                    continue
            
                obs = up2dateUtils.genObsoleteTupleFromHdr(hdr)
                if obs:
                    self.obsList = self.obsList + obs

        # nowwe have the package list, convert it to xmlrpc style
        # presentation and dump it
        pkgList.sort(lambda a, b: cmp(a[0], b[0]))

        return pkgList
