#!/usr/bin/perl -w
# copyright-file -- lintian collector script

# Copyright © 1998 Richard Braakman
# Copyright © 2019 Felix Lechner
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, you can find it on the World Wide
# Web at http://www.gnu.org/copyleft/gpl.html, or write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.

package Lintian::coll::copyright_file;

no lib '.';

use strict;
use warnings;
use autodie;

use lib "$ENV{'LINTIAN_ROOT'}/lib";
use Lintian::Util qw(internal_error gunzip_file is_ancestor_of);

use File::Copy qw(copy);

sub collect {
    my ($pkg, $type, $dir) = @_;

    my $unpackedpath = "$dir/unpacked";
    return unless -d $unpackedpath;

    my $copyrightpath = "$dir/copyright";
    unlink($copyrightpath)
      if -e $copyrightpath;

    my $packagepath = "$unpackedpath/usr/share/doc/$pkg";
    return unless -d $packagepath;

    # do not proceed if the parent dir is outside the package
    return unless is_ancestor_of($unpackedpath, $packagepath);

    my $packagecopyrightpath = "$packagepath/copyright";

    # make copy if symlink; hardlink could dangle; also check link path
    if (-l $packagecopyrightpath) {
        my $link = readlink($packagecopyrightpath);
        unless ($link =~ /\.\./
            || ($link =~ m%/% && $link !~ m%^[^/]+(?:/+[^/]+)*\z%)) {
            copy($packagecopyrightpath, $copyrightpath)
              or internal_error("cannot copy $packagecopyrightpath: $!");
        }
    } elsif (-f $packagecopyrightpath) {
        link($packagecopyrightpath, $copyrightpath);
    } elsif (-f "$packagecopyrightpath.gz") {
        gunzip_file("$packagecopyrightpath.gz", $copyrightpath);
    }

    return;
}

collect(@ARGV) unless caller;

1;

# Local Variables:
# indent-tabs-mode: nil
# cperl-indent-level: 4
# End:
# vim: syntax=perl sw=4 sts=4 sr et
