#include <alloca.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <rpmlib.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define FILENAME_TAG 1000000

int main(int argc, char ** argv) {
    char buf[300];
    int fd;
    Header h;
    int count, type;
    int end;
    char * name, * filename, * version, * release;

    if (argc != 2) {
	fprintf(stderr, "usage: dmphdlist <dir>\n");
	exit(1);
    }

    strcpy(buf, argv[1]);
    strcat(buf, "/RedHat/base/hdlist");
    
    fd = open(buf, O_RDONLY, 0644);
    if (fd < 0) {
	fprintf(stderr,"error opening file %s: %s\n", buf, strerror(errno));
	return 1;
    }

    end = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    while (end > lseek(fd, 0, SEEK_CUR)) {
	h = headerRead(fd, HEADER_MAGIC_YES);
	if (!h) {
	    fprintf(stderr, "error reading header at %d\n", 
		    (int) lseek(fd, 0, SEEK_CUR));
	    exit(1);
	}

	headerGetEntry(h, FILENAME_TAG, &type, (void *) &filename, &count);
	headerGetEntry(h, RPMTAG_NAME, &type, (void *) &name, &count);
	headerGetEntry(h, RPMTAG_VERSION, &type, (void *) &version, &count);
	headerGetEntry(h, RPMTAG_RELEASE, &type, (void *) &release, &count);

	printf("%-35s\t==\t%s %s %s\n", filename, name, version, release);

	headerFree(h);
    }

    close(fd);

    return 0;
}
