#!/usr/bin/perl

# $OpenBSD: find-all-conflicts,v 1.7 2004/02/12 13:55:45 espie Exp $
# Copyright (c) 2000
# Marc Espie.  All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Neither the name of OpenBSD nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY ITS AUTHOR AND THE OpenBSD project ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

# check all packages in the current directory, and report conflicts which
# are not apparent in @pkgcfl.

use strict;

use File::Spec;
use File::Path;
use OpenBSD::PackageLocator;
use OpenBSD::PackageInfo;
use OpenBSD::PackingList;
use OpenBSD::PkgCfl;

sub analyze 
{
	my ($plist, $all) = @_;
	my $pkgname = $plist->pkgname();

	for my $item (@{$plist->{items}}) {
		next unless $item->IsFile();
		my $file= File::Spec->canonpath($item->fullname());
		unless (defined $all->{$file}) {
			$all->{$file} = [];
		}
		push @{$all->{$file}}, $pkgname;
	}
}

sub show_problems
{
    my ($h, $conflicts) = @_;

    while (my ($key, $l) = each %$h) {
	    if (@$l > 1) {
		my $notfound = 0;
		# create a list of unconflicting packages.
		my @l2 = ();
		for my $pkg (@$l) {
		    next if $conflicts->{$pkg}->conflicts_with(
			    grep { $_ ne $pkg } (@$l));
		    push(@l2, $pkg);
		}
		if (@l2 != 0) {
		    print "$key: ", join(',', @l2), "\n";
		}
	    }
    }
}

my $filehash={};
my %dirhash=();
my $conflicts={};

print "Scanning packages\n";
print "-----------------\n";
if (@ARGV==0) {
	@ARGV=(<*.tgz>);
}
for my $pkgname (@ARGV) {
	print STDERR "$pkgname\n";
	my $true_package = OpenBSD::PackageLocator->find($pkgname);
	next unless $true_package;
	my $dir = $true_package->info();
	$true_package->close();
	my $plist = OpenBSD::PackingList->fromfile($dir.CONTENTS);
	rmtree($dir);
	$conflicts->{$plist->pkgname()} = 
	    OpenBSD::PkgCfl->make_conflict_list($plist);
	analyze($plist, $filehash);
}

print "File problems:\n";
print "-------------\n";
show_problems($filehash, $conflicts);
