#!/usr/bin/perl -w

# $OpenBSD: make-plist,v 1.15 2001/08/23 09:13:19 espie Exp $

#  Copyright (c) 1999 Marc Espie
# 
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. All advertising materials mentioning features or use of this software
#     must display the following acknowledgement:
# 	This product includes software developed by the OpenBSD project
#
#  4. Neither the name of the OpenBSD project 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 THE AUTHOR ``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 AUTHOR 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.
# 


use strict;


use File::Find;
use File::Spec;

my %annotated;
my $keep = '';
my $manual = 0;

sub annotate
{
	my $filename = shift;
	my ($mode, $owner, $group, $nocheck) = ('', '', '', '');
	open(OLDFILE, '<', $filename) or die "Can't read $filename";
	while(<OLDFILE>) {
		chomp;
		if (m/^\@mode\s*/) {
			$mode = $';
		} elsif (m/^\@owner\s*/) {
			$owner = $';
		} elsif (m/^\@group\s*/) {
			$group = $';
		} elsif (m/^\@comment\s+no checksum$/) {
			$nocheck = 1;
		} elsif (m/^\@option no-default-conflict/||m/^\@pkgcfl/) {
			$keep="$keep$_\n";
		} elsif (m/^\@exec\s+/ || m/^\@unexec\s+/) {
			$_=$';
			# we don't warn for stuff we probably added...
			next if m/^mkdir -p/||m/^install-info /;
			$manual = 1;
		} elsif (m/^\@/) {
			next;
		} elsif (m/^\!?\%\%(.*)\%\%/) {
			my $frag = $1;
			if ($frag ne "SHARED") {
				$keep="$keep$_\n";
				$manual = 1;
			}
		} elsif (m/\$\{.*\}/) {
			$manual = 1;
		}

		if ("$mode$owner$group$nocheck" ne '') {
			$annotated{$_} = [ $mode, $owner, $group, $nocheck ];
			$nocheck = '';
		}
	}
}

my ($plist, $pshared);
my @backsubst;

my (%newdir, %occupied, %ldconfig, %has_stuff, %infodir, @files, @libfiles);
die "Update bsd.port.mk" if @ARGV == 0;
my $plistdir = shift;
die "Update bsd.port.mk" if -f $plistdir;
$plist = File::Spec->catfile($plistdir, 'PLIST');
$pshared = File::Spec->catfile($plistdir, 'PFRAG.shared');
if (-e "$plist.orig" or -e "$pshared.orig") {
	die "You must clean up old files first";
}
if (-e $plist) {
    annotate($plist);
    rename($plist, "$plist.orig") or die "Can't rename $plist to $plist.orig";
}

if (-e $pshared) {
    annotate($pshared);
    rename($pshared, "$pshared.orig") or die "Can't rename $pshared to $pshared.orig";
}

open(PLIST, '>', $plist) or die "Can't write to $plist";
select PLIST;

for (@ARGV) {
	if (m/\=/) {
		my $back = $`;
		my $v = $';
		push(@backsubst, ["\${$back}", $v]) if $v ne '';
	}
}

print "\@comment \$OpenBSD\$\n$keep";

# compare all files against those dates
my @date = (stat $ENV{INSTALL_PRE_COOKIE})[9, 10];

# prefix to remove from everything
my $base = $ENV{PREFIX};

my $destdir = $ENV{DESTDIR};

# read an mtree file, and produce the corresponding directory hierarchy
sub parse_mtree {
		# start under current DESTDIR, usually
	my $current = shift;
	local(*FILE);
	my %mtree;
	open FILE, $ENV{MTREE_FILE};
	while(<FILE>) {
		chomp;
		s/^\s*//;
		next if /^\#/ || /^\//;
		s/\s.*$//;
		next if /^$/;
		if ($_ eq '..') {
			$current =~ s|/[^/]*$||;
			next;
		} else {
			$current.="/$_";
		}
		$_ = $current;
		while (s|/\./|/|)	{}
		$mtree{$_} = 1;
	}
	close FILE;
	return \%mtree;
}

sub strip {
	local($_) = shift;
	s|^\Q$base\E/||;
	for my $l (@backsubst) {
		my $v = $l->[1];
		my $r = $l->[0];
		s/\Q$v\E/$r/g;
	}
	# If the resulting name is arch-dependent, we warn.
	# We don't fix it automatically, as this may need special handling.
	if (m/i386|m68k|sparc/) {
	    print STDERR "make-plist: generated plist contains arch-dependent\n"; 
	    print STDERR "\t$_\n";
	}
	return $_;
}

sub add_info {
	my ($header, $infodir) = @_;
	for my $d (sort (keys %$infodir) ) {
		for my $f (sort @{$infodir->{$d}}) {
			my $d2 = strip($d);
			print "$header --info-dir=\%D/$d2 \%D/$d2/$f\n";
		}
	}
}

# recursive traversal: mark specific `info' dirs, `ldconfig' dirs,
# and potentially modified dirs

find(
	sub {
		my @cdate = (lstat $_)[9, 10];
		if ($cdate[0] >= $date[0] || $cdate[1] >= $date[1]) {
			$has_stuff{$File::Find::dir} = 1;
			if (-d _) {
				$newdir{$File::Find::name} = 1;
			} else {
				if (/\.so\.\d+\.\d+$/) {
					$ldconfig{$File::Find::dir} = 1;
					push(@libfiles, $File::Find::name);
				} else {
					push(@files, $File::Find::name);
					if (/\.info$/) {
						my $d = $File::Find::dir;
						$infodir{$d} = [] unless defined $infodir{$d};
						push(@{$infodir{$d}}, $_);
					}
				}
			}
		} else {
			$occupied{$File::Find::dir} = 1;
		}
	}, $base);


# occupied marks a dir that was already there... 
# so all parents had to be around too
for my $d (keys %occupied) {
	while ($d ne '') {
		undef $newdir{$d} if defined $newdir{$d};
		$d =~ s|/.*?/?$||;
	}
}

# make sure mtree is removed 
my $mtree = parse_mtree($destdir);
for my $d (keys %$mtree) {
	undef $newdir{$d}
}

add_info('@unexec install-info --delete', \%infodir);

sub handle_file
{
    my $fname = strip(shift);
    my $string = "$fname\n";

    if (defined $annotated{$fname}) {
    	my ($mode, $owner, $group, $nocheck) = @{$annotated{$fname}};
	if ($mode ne '') {
		$string="\@mode $mode\n$string\@mode\n";
	}
	if ($owner ne '') {
		$string="\@owner $owner\n$string\@owner\n";
	}
	if ($group ne '') {
		$string="\@group $group\n$string\@group\n";
	}
	if ($nocheck ne '') {
		$string="\@comment no checksum\n$string";
	}
    }
    print $string;
}

for my $f (sort @files) {
	handle_file($f) unless ($f =~ m|/dir$|) && (defined $infodir{$`});
}

if (@libfiles > 0) {
    	print "\%\%SHARED\%\%\n";
	open(SHARED, ">$pshared") or die "Can't write to $pshared";
	print SHARED "\@comment \$OpenBSD\$\n";
	for my $f (sort @libfiles) {
	    print SHARED strip($f), "\n";
	}
	for my $d (sort (keys %ldconfig)) {
		if (defined $newdir{$d}) {
			print SHARED "NEWDYNLIBDIR(\%D/", strip($d), ")\n";
		} else {
			print SHARED "DYNLIBDIR(\%D/", strip($d), ")\n";
		}
	}
	close SHARED;
}

for my $d (sort { $b cmp $a } (grep { $newdir{$_} } (keys %newdir) ) ) {
	# case of new directory that does not hold anything: it's marked
	# for removal, but it must exist first
	if (!$has_stuff{$d}) {
		print "\@exec mkdir -p \%D/", strip($d), "\n";
	}
	print "\@dirrm ",strip($d), "\n";
}
	
add_info('@exec install-info', \%infodir);

if ($manual) {
	print STDERR "make plist: subst/frag/exec/unexec spotted in original file\n";
	print STDERR "\tMay require manual intervention\n";
}
