#!/bin/env perl
#
# $Id: rm-patchdata.pl,v 1.4 1994/11/03 13:18:28 casper Exp casper $
#
# Only keep data of the last patch.
# Will only remove patches which aren't saved, unless
# -f specified.  Don't remove the last patch installed.
# Will only tell what will be done, unless -r specified.
# Other patches specified on the command line will be removed as
# well.
#
# This program is being subsumed by fastpatch.pl.
#
# Casper Dik (casper@fwi.uva.nl)
#

require 'getopts.pl';

$0 =~ s:.*/::;
if (!&Getopts('fr')) {
    print STDERR "Usage: $0 [-f] [-r] [ patch ... ]\n";
    exit 1;
}

for (@ARGV) {
    s/-.*//;  # Remove revision
    $obs{$_} = "";
}

select(STDOUT); $| = 1;
select(STDERR); $| = 1;

for $f  (</var/sadm/pkg/*/pkginfo>) {
    open(STDIN,"<$f") || die "$f: $!\n";
    ($pkg = $f) =~ s:^/var/sadm/pkg/(.*)/pkginfo$:$1:;
    while (<STDIN>) {
	chop;
	if (/^SUNW_PATCHID=/) {
	    $patch = $';
	    ($base,$rev) = split('-', $patch);
	    $revs{$base} = $rev
		if (!defined($revs{$base}) || $revs{$base} < $rev);
	    if (defined($pkg{$patch})) {
		$pkg{$patch} .= " " . $pkg;
	    } else {
		$pkg{$patch} = $pkg;
	    }
	} elsif (/^SUNW_OBSOLETES=/) {
	    for $p (split(',',$')) {
		($base,$rev) = split('-', $p);
		$obs{$base} = "";
	    }
	}

    }
}

for $patch (keys(%pkg)) {
    # Don't obsolete patches that have old files saved, unless -a specified.
    ($base, $rev) =  split('-', $patch);
    if (($rev < $revs{$base} || defined($obs{$base}))
		&& ($opt_f || ! -f "/var/sadm/patch/$patch/.oldfilessaved")) {
	$obsolete{$patch} = "";
    }
}
open(PATCHADMIN,">/tmp/admin.$$");

print PATCHADMIN <<EOF ;
mail=
instance=unique
partial=nocheck
runlevel=nocheck
idepend=quit
rdepend=quit
space=quit
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
EOF

close(PATCHADMIN);

for $patch (keys(%obsolete)) {
    # Remove the patch packages, followed by the patch directory.
    if (defined($opt_r)) {
	print "Removing: $patch\n";
	system "pkgrm -a /tmp/admin.$$ -n $pkg{$patch}";
	system "rm -rf /var/sadm/patch/$patch";
    } else {
	print "#$patch would be removed with the following commands:\n";
	print "pkgrm -a /tmp/admin.$$ -n $pkg{$patch}\n";
	print "rm -rf /var/sadm/patch/$patch\n";
    }
}
unlink ("/tmp/admin.$$");
