#! /usr/bin/env perl
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#

# reads a list of dependency files from a file, opens and
# concatenates them, while eliding duplicate nop rules.
use File::Spec;

sub read_depfiles($)
{
    my $name = shift;
    my $depfh;
    my @files;
    open ($depfh, $name) || die "Can't open list of dependencies: $name: $!";
    while (<$depfh>) {
	push @files, split(/\s+/, $_);
    }
    close ($depfh);

#    print STDERR "dep files: " . join ("'", @files) . "\n";
    return @files;
}

my @depfiles = read_depfiles (shift @ARGV);

my %rules;
print "# concatenated, reduced dependencies generated by solenv/bin/concat-deps.pl\n";
print "# generated with \$(SRCDIR) = $ENV{SRCDIR}\n";
print "# generated with \$(OUTDIR) = $ENV{OUTDIR}\n";

my $boost_path = $ENV{OUTDIR} . '/inc/boost/';

for my $fname (@depfiles) {
    my $fileh;

    next if ($fname eq '');
    open ($fileh, $fname) || die "Can't open $fname: $!\n";

    my $last = '';
    my $rule_count = 0;
    my $with_boost_count = 0;
    while (<$fileh>) {
        # canonicalise path
        m/^(\s*)([^\s\n:]*)(.*\n?)$/;
        my $pre = $1;
        my $path = $2;
        my $post = $3;
        $rule_count++ if ($post =~ m/:/);
        if (length($path) > 0 && index($path,$ENV{SRCDIR}) == 0) {
            $path = File::Spec->rel2abs($2);
            if (index($path,$ENV{OUTDIR}) == 0) {
                my $solverpath = substr($path, length($ENV{OUTDIR}));
                if ($solverpath =~ m|/inc/boost/|) {
                    if ($with_boost_count != $rule_count || !($post =~ m/\\/)) {
                        $path = '$(OUTDIR)/inc/boost/deliver.log';
                        $with_boost_count = $rule_count;
                    } else { # elide it
                        $path = ''; $pre = ''; $post = '';
                    }
                } else {
                    $path = "\$(OUTDIR)" . $solverpath;
                }
            } else {
                $path = "\$(SRCDIR)" . substr($path, length($ENV{SRCDIR}));
            }
        }
        $line = "$pre$path$post";

        if ($line eq "\n") {
            if ($last =~ /^(.*):\s*$/) {
                if (defined $rules{$1}) {
                    $last = '';
                    next;
                }
                $rules{$1} = 1;
            }
        }
        print $last;
        $last = $line;
    }
    print "$last\n"; # in case of missing newline

    close ($fileh);
}
