#!/bin/ksh
#
# $Id: diffpkg 431 2006-03-22 01:19:51Z comand $
#
# Copyright 2006 Cory Omand <comand@blastwave.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This software is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# diffpkg - compare the manifests of two packages (does not
#           report file content or size changes).
#

F1=$1
F2=$2

if [ -z "$F2" ] || [ ! -f $F1 ] || [ ! -f $F2 ]; then
    print "Usage: $0 <pkg1> <pkg2>"
    exit 1
fi

# Create temp dir
TMPDIR=/tmp/compare.$$
mkdir -p $TMPDIR

# Process F1
TF1=$TMPDIR/`basename $F1`
cp $F1 $TMPDIR
gunzip $TF1 >/dev/null 2>&1
[ $? -eq 0 ] && TF1=$TMPDIR/`basename $TF1 .gz`

TF1NAME=`pkginfo -d $TF1 | cut -f2 -d' '`
TF1ROOT=$TMPDIR/${TF1NAME}-1
pkgadd -s $TMPDIR -d $TF1 $TF1NAME >/dev/null 2>&1
es=$?
if [ $es -ne 0 ]; then
    echo "Failed to spool $F1: pkgadd returned exit code $es"
    exit $es
fi
mv $TMPDIR/$TF1NAME $TF1ROOT
rm -f $TF1

# Process F2
TF2=$TMPDIR/`basename $F2`
cp $F2 $TMPDIR
gunzip $TF2 >/dev/null 2>&1
[ $? -eq 0 ] && TF2=$TMPDIR/`basename $TF2 .gz`

TF2NAME=`pkginfo -d $TF2 | cut -f2 -d' '`
TF2ROOT=$TMPDIR/${TF2NAME}-2
pkgadd -s $TMPDIR -d $TF2 $TF2NAME >/dev/null 2>&1
es=$?
if [ $es -ne 0 ]; then
    echo "Failed to spool $F1: pkgadd returned exit code $es"
    exit $es
fi
mv $TMPDIR/$TF2NAME $TF2ROOT
rm -f $TF2

if [ "$TF1NAME" != "$TF2NAME" ]; then
    echo "Cannot compare packages $TF1NAME and $TF2NAME"
    rm -rf $TMPDIR
    exit 2
fi

# Sort manifests
nawk 'NF > 6 { print $4 }' $TF1ROOT/pkgmap | sort | uniq > $TF1ROOT/manifest
nawk 'NF > 6 { print $4 }' $TF2ROOT/pkgmap | sort | uniq > $TF2ROOT/manifest

# Compare manifests
diff -u $TF1ROOT/manifest $TF2ROOT/manifest > $TMPDIR/manifest.diff
if [ -s $TMPDIR/manifest.diff ]; then
    cat $TMPDIR/manifest.diff
else
    echo "Package lists are the same"
fi

# Clean up
rm -rf $TMPDIR
exit 0
