#!/usr/bin/python
#
# whichcd.py - figure out which cd a given package is on
#
# Copyright 2003 Red Hat, Inc.
# Author: Jeremy Katz <katzj@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import rpm
import os
import sys

def usage():
    print "%s <package> [headerlist]" % (sys.argv[0])
    print "where <package> is the package you're looking for and "
    print "[headerlist] is optionally the location of the header list"
    print "(defaults to the one in /usr/share/comps"

# hijacked from anaconda
def getArch ():
    arch = os.uname ()[4]
    if (len (arch) == 4 and arch[0] == 'i' and
        arch[2:4] == "86"):
        arch = "i386"

    if arch == "sparc64":
        arch = "sparc"

    if arch == "ppc64":
        arch = "ppc"

    if arch == "s390x":
        arch = "s390"

    return arch
    
if len(sys.argv) < 2 or len(sys.argv) > 3:
    usage()
    sys.exit(0)

if len(sys.argv) == 3:
    hdrlist = sys.argv[2]
else:
    hdrlist = "/usr/share/comps/%s/hdlist" %(getArch(),)

hdlist = rpm.readHeaderListFromFile(hdrlist)
pkgname = sys.argv[1]
found = 0

for hdr in hdlist:
    if hdr[rpm.RPMTAG_NAME] == pkgname:
        print "%s-%s-%s.%s.rpm is on disc %s" %(pkgname,
                                                hdr[rpm.RPMTAG_VERSION],
                                                hdr[rpm.RPMTAG_RELEASE],
                                                hdr[rpm.RPMTAG_ARCH],
                                                hdr[1000002])
        found = 1

if not found:
    print "Unable to find %s in header list" %(pkgname,)
