#!/usr/bin/python3
#---------------------------------------------------------------
# Project         : Linux-Mandrake
# Module          : rpm-rebuilder
# File            : check-distrib
# Version         : $Id: check-distrib,v 1.5 2003/08/05 19:10:11 flepied Exp $
# Author          : Frederic Lepied
# Created On      : Tue May 16 06:55:15 2000
#---------------------------------------------------------------

import os
import rpm
import sys

# check if we use a rpm version compatible with 4.2
try:
    if rpm.RPMTAG_SOURCEPACKAGE:
        v42=1
except AttributeError:
    v42=0

def get_header_and_type(rpm_path):
        fd = os.open(rpm_path, os.O_RDONLY)
    
	if v42:
		ts=rpm.TransactionSet()
		# Don't check signatures here...
		ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
		header=ts.hdrFromFdno(fd)
		if header[rpm.RPMTAG_SOURCEPACKAGE]:
		    is_source=1
		else:
		    is_source=0
	else:
		(header, is_source)=rpm.headerFromPackage(fd)
		
        os.close(fd)
	return  (header, is_source)	


def check(srcdir, bindir, arch):
    srpms = os.listdir(srcdir)
    rpms = os.listdir(bindir)
    invalid_srpms = srpms[:]

    for p in rpms:
        try:
            # Create a package object from the file name
            (header, is_source)=get_header_and_type(bindir + '/' + p)
	except KeyboardInterrupt:
	    sys.stderr.write("Interrupted\n")
	    sys.exit(1)
        except:
            print "E: invalid-file", p
            continue
        
	try:
            src = header[rpm.RPMTAG_SOURCERPM]
            if src in srpms:
                try:
                    invalid_srpms.remove(src)
                except ValueError:
                    pass
            else:
                print "E: no-source", p
        except:
            print "E: invalid-binary", p

    for p in invalid_srpms:
        try:
            # Create a package object from the file name
            (header, is_source)=get_header_and_type(srcdir + '/' + p)
       	except KeyboardInterrupt:
	    sys.stderr.write("Interrupted\n")
	    sys.exit(1)
	except:
            print "E: invalid-file", p
            continue

        try:
            exclusivearch = header[rpm.RPMTAG_EXCLUSIVEARCH]
            if exclusivearch == None or arch in exclusivearch:
                print "E: no-binary", p
        except:
            print "E: invalid-source", p

if len(sys.argv) != 4:
    print "usage:", sys.argv[0], "<src dir> <bin dir> <arch>"
    print "check coherence of binary and source rpms"
    sys.exit(1)
    
check(sys.argv[1], sys.argv[2], sys.argv[3])

# Local variables:
# mode: python
# End:
#
# check-distrib ends here
