#!/usr/bin/perl

# Copyright © 1998 Richard Braakman
# Copyright © 2008 Frank Lichtenheld
# Copyright © 2008, 2009 Russ Allbery
# Copyright © 2014 Niels Thykier
# Copyright © 2020 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.

# The harness for Lintian's test suite.  For detailed information on
# the test suite layout and naming conventions, see t/tests/README.
# For more information about running tests, see
# doc/tutorial/Lintian/Tutorial/TestSuite.pod

use v5.20;
use warnings;
use utf8;

use Const::Fast;
use Cwd qw(realpath);
use File::Basename qw(dirname);

# neither Path::This nor lib::relative are in Debian
use constant THISFILE => realpath __FILE__;
use constant THISDIR => dirname realpath __FILE__;

# use Lintian modules that belong to this program
use lib THISDIR . '/../lib';

use Cwd qw(getcwd);
use Capture::Tiny qw(capture_merged);
use File::Copy;
use File::Find::Rule;
use File::stat;
use Getopt::Long;
use IPC::Run3;
use List::Compare;
use MCE::Loop;
use Path::Tiny;
use Syntax::Keyword::Try;
use Time::Duration;
use Time::Moment;
use Time::Piece;
use Unicode::UTF8 qw(encode_utf8 decode_utf8);

use Lintian::IPC::Run3 qw(safe_qx);

use Test::Lintian::Build qw(build_subject);
use Test::Lintian::ConfigFile qw(read_config);
use Test::Lintian::Helper
  qw(rfc822date cache_dpkg_architecture_values get_latest_policy get_recommended_debhelper_version);
use Test::Lintian::Hooks qw(sed_hook sort_lines calibrate);
use Test::Lintian::Prepare qw(prepare);

const my $EMPTY => q{};
const my $SPACE => q{ };
const my $INDENT => $SPACE x 4;
const my $NEWLINE => qq{\n};
const my $SLASH => q{/};
const my $COLON => q{:};
const my $ARROW => q{>>>};
const my $YES => q{yes};
const my $NO => q{no};

const my $WIDELY_READABLE => oct(22);

my $processing_start = Time::Moment->from_string(gmtime->datetime . 'Z');

# whitelist the environment we permit to avoid things that mess up
# tests, like CFLAGS, DH_OPTIONS, DH_COMPAT, DEB_HOST_ARCH
# TODO: MAKEFLAGS - some of the tests don't cope too well with it
my %PRESERVE_ENV = map { $_ => 1 } qw(
  NO_PKG_MANGLE
  PATH
  TMPDIR
  CCACHE_DIR
);

my @disallowed = grep { !exists $PRESERVE_ENV{$_} } keys %ENV;

delete $ENV{$_} for @disallowed;

# Standard pipeline installs ccache; causes write permission errors on Salsa
# https://salsa.debian.org/salsa-ci-team/pipeline/-/issues/164
$ENV{CCACHE_DISABLE} = 1;

# Ubuntu auto-builders run pkg-mangle which messes up test packages
$ENV{NO_PKG_MANGLE} //= 'true';

$ENV{LINTIAN_BASE} = realpath(THISDIR . '/..')
  // die encode_utf8('Cannot resolve LINTIAN_BASE');

# options
my $debug;
my $dump_logs = 1;
my $force_rebuild;
my $numjobs;
my $outpath;
my $verbose = 0;

Getopt::Long::Configure('bundling');
unless (
    Getopt::Long::GetOptions(
        'B|force-rebuild'  => \$force_rebuild,
        'd|debug+'         => \$debug,
        'j|jobs:i'         => \$numjobs,
        'L|dump-logs!'     => \$dump_logs,
        'v|verbose'        => \$verbose,
        'w|work-dir:s'     => \$outpath,
        'h|help'           => sub {usage(); exit;},
    )
) {
    usage();
    die;
}

# check number of arguments
die encode_utf8('Please use -h for usage information.')
  if @ARGV > 1;

# get arguments
my ($testset) = @ARGV;

# default test set
$testset ||= 't';

# check test set directory
die encode_utf8("Cannot find testset directory $testset")
  unless -d $testset;

# make sure testset is an absolute path
$testset = path($testset)->absolute->stringify;

# calculate a default test work directory if none given
$outpath ||= path($testset)->parent->stringify . '/debian/test-out';

# create test work directory unless it exists
path($outpath)->mkpath
  unless -e $outpath;

# make sure test work path is a directory
die encode_utf8("Test work directory $outpath is not a directory")
  unless -d $outpath;

say encode_utf8($EMPTY);

# tie verbosity to debug
$verbose = 1 + $debug if $debug;

# can be 0 without value ("-j"), or undef if option was not specified at all
$numjobs ||= default_parallel();
say encode_utf8("Running up to $numjobs tests concurrently")
  if $numjobs > 1 && $verbose >= 2;

$ENV{'DUMP_LOGS'} = $dump_logs//$NO ? $YES : $NO;

# Disable translation support in dpkg as it is a considerable
# unnecessary overhead.
$ENV{'DPKG_NLS'} = 0;

my $helperpath = "$testset/../bin";
if (-d $helperpath) {
    my $helpers = path($helperpath)->absolute->stringify
      // die encode_utf8("Cannot resolve $helperpath: $!");
    $ENV{'PATH'} = "$helpers:$ENV{'PATH'}";
}

# get architecture
cache_dpkg_architecture_values();
say encode_utf8("Host architecture is $ENV{'DEB_HOST_ARCH'}.");

# get latest policy version and date
($ENV{'POLICY_VERSION'}, $ENV{'POLICY_EPOCH'}) = get_latest_policy();
say encode_utf8("Latest policy version is $ENV{'POLICY_VERSION'} from "
      . rfc822date($ENV{'POLICY_EPOCH'}));

# get current debhelper compat level; do not name DH_COMPAT; causes conflict
$ENV{'DEFAULT_DEBHELPER_COMPAT'} = get_recommended_debhelper_version();
say encode_utf8(
"Using compat level $ENV{'DEFAULT_DEBHELPER_COMPAT'} as a default for packages built with debhelper."
);

say encode_utf8($EMPTY);

# print environment
my @vars = sort keys %ENV;
say encode_utf8('Environment:') if @vars;
for my $var (@vars) { say encode_utf8($INDENT . "$var=$ENV{$var}") }

say encode_utf8($EMPTY);

my $status = 0;

my $recipe_root = "$testset/recipes";

# find build specifications
my @recipes = map { path($_)->parent->stringify }
  sort File::Find::Rule->relative->name('build-spec')->in($recipe_root);

# prepare output directories
say encode_utf8(
    'Preparing the sources for '. scalar @recipes. ' test packages.')
  if @recipes;

# for filled templates
my $source_root = "$outpath/package-sources";

# for built test packages
my $build_root = "$outpath/packages";

my @source_paths
  = map { path($_)->absolute($source_root)->stringify } @recipes;
my @build_paths = map { path($_)->absolute($build_root)->stringify } @recipes;

# remove obsolete package sources
my @found_sources = map { path($_)->parent->absolute->stringify; }
  File::Find::Rule->file->name('fill-values')->in($source_root);
my $sourcelc = List::Compare->new(\@found_sources, \@source_paths);
my @obsolete_sources = $sourcelc->get_Lonly;
path($_)->remove_tree for @obsolete_sources;

# remove obsolete built packages
my @found_builds = map { path($_)->parent->absolute->stringify; }
  File::Find::Rule->file->name('source-files.sha1sums')->in($build_root);
my $packagelc= List::Compare->new(\@found_builds, \@build_paths);
my @obsolete_builds = $packagelc->get_Lonly;
path($_)->remove_tree for @obsolete_builds;

# remove empty directories
for my $folder (@obsolete_sources, @obsolete_builds) {
    my $candidate = path($folder)->parent;
    while ($candidate->exists && !$candidate->children) {
        rmdir $candidate->stringify;
        $candidate = $candidate->parent;
    }
}

$ENV{PERL_PATH_TINY_NO_FLOCK} =1;

$SIG{INT} = sub { MCE::Loop->finish; die encode_utf8("Caught a sigint $!") };
my $mce_loop = MCE::Loop->init(
    max_workers => $numjobs,
    chunk_size => 1,
    flush_stdout => 1,
    flush_stderr => 1,
);

my %failedprep = mce_loop {
    my ($mce, $chunk_ref, $chunk_id) = @_;

    prepare_build($mce, $_);
}
@recipes;

if (%failedprep) {
    say encode_utf8($EMPTY);
    say encode_utf8('Failed preparation tasks:');
    for my $recipe (sort keys %failedprep) {
        say encode_utf8($EMPTY);
        say encode_utf8($ARROW
              . $SPACE
              . path("$recipe_root/$recipe")->relative->stringify
              . $COLON);
        print encode_utf8($failedprep{$recipe});
    }

    MCE::Loop->finish;
    exit 1;

} else {
    say encode_utf8('Package sources are ready.');
}

say encode_utf8($EMPTY);

my %failedbuilds = mce_loop {
    my ($mce, $chunk_ref, $chunk_id) = @_;

    build_package($mce, $_, $chunk_id, scalar @recipes);
}
@recipes;

$SIG{INT} = 'DEFAULT';
MCE::Loop->finish;

if (%failedbuilds) {
    say encode_utf8($EMPTY);
    say encode_utf8('Failed build tasks:');
    for my $recipe (sort keys %failedbuilds) {
        say encode_utf8($EMPTY);
        say encode_utf8($ARROW
              . $SPACE
              . path("$recipe_root/$recipe")->relative->stringify
              . $COLON);
        print encode_utf8($failedbuilds{$recipe});
    }

    exit 1;
} else {
    say encode_utf8('All test packages are up to date.');
}

say encode_utf8($EMPTY);

my $processing_end = Time::Moment->from_string(gmtime->datetime . 'Z');
my $duration = duration($processing_start->delta_seconds($processing_end));
say encode_utf8("Building the test packages took $duration.");

say encode_utf8($EMPTY);

exit 0;

# program is done

sub prepare_build {
    my ($mce, $recipe) = @_;

    # label process
    $0 = "Lintian prepare test: $recipe";

    # destination
    my $source_path = "$source_root/$recipe";

    my $error;

    # capture output
    my $log_bytes =capture_merged {

        try {

            # remove destination
            path($source_path)->remove_tree
              if -e $source_path;

            # prepare
            prepare("$recipe_root/$recipe/build-spec",
                $source_path, $testset, $force_rebuild);

        } catch {
            # catch any error
            $error = $@;
        }
    };

    my $log = decode_utf8($log_bytes);

    # save log;
    my $logfile = "$source_path.log";
    path($logfile)->spew_utf8($log) if $log;

    $mce->gather($recipe, $error)
      if length $error;

    return;
}

sub build_package {
    my ($mce, $recipe, $position, $total) = @_;

    # set a predictable locale
    $ENV{'LC_ALL'} = 'C';

    # many tests create files via debian/rules
    umask $WIDELY_READABLE;

    # get destination
    my $source_path = "$source_root/$recipe";
    my $build_path = "$build_root/$recipe";

    my $savedir = getcwd;
    chdir $source_path
      or die encode_utf8("Cannot change to directory $source_path");

    my $sha1sums_bytes;
    run3('find . -type f -print0 | sort -z | xargs -0 sha1sum',
        \undef, \$sha1sums_bytes);

    chdir $savedir
      or die encode_utf8("Cannot change to directory $savedir");

    my $sha1sums = decode_utf8($sha1sums_bytes);

    my $checksum_path = "$build_path/source-files.sha1sums";
    if (-r $checksum_path) {
        my $previous = path($checksum_path)->slurp_utf8;

        # only rebuild if needed
        # also need to look for build subject
        return
          if $sha1sums eq $previous;
    }

    $0 = "Lintian build test: $recipe [$position/$total]";
    say encode_utf8('Building in '
          . path($build_path)->relative->stringify
          . " [$position/$total]");

    path($build_path)->remove_tree
      if -e $build_path;
    path($build_path)->mkpath;

    # read dynamic file names
    my $runfiles = "$source_path/files";
    my $files = read_config($runfiles);

    my $error;

    my $log_bytes = capture_merged {

        try {
            # call runner
            build_subject($source_path, $build_path);

        } catch {
            # catch any error
            $error = $@;
        }
    };

    my $log = decode_utf8($log_bytes);

    # delete old runner log
    my $betterlogpath= $build_path . $SLASH . $files->unfolded_value('Log');
    if (-e $betterlogpath) {
        unlink $betterlogpath
          or die encode_utf8("Cannot unlink $betterlogpath");
    }

    # move the early log for directory preparation to position of runner log
    my $earlylogpath = "$source_path.log";
    move($earlylogpath, $betterlogpath) if -e $earlylogpath;

    # append runner log to population log
    path($betterlogpath)->append_utf8($log) if length $log;

    # add error if there was one
    path($betterlogpath)->append_utf8($error) if length $error;

    path($checksum_path)->spew_utf8($sha1sums)
      unless length $error;

    $mce->gather(path($build_path)->relative->stringify, $error)
      if length $error;

    return;
}

=item default_parallel

=cut

# Return the default number of parallelization to be used
sub default_parallel {
    # check cpuinfo for the number of cores...
    my $cpus = decode_utf8(safe_qx('nproc'));
    if ($cpus =~ m/^\d+$/) {
        # Running up to twice the number of cores usually gets the most out
        # of the CPUs and disks but it might be too aggressive to be the
        # default for -j. Only use <cores>+1 then.
        return $cpus + 1;
    }

    # No decent number of jobs? Just use 2 as a default
    return 2;
}

sub usage {
    my $message =<<"END";
-Usage: $0 [options] [-j [<jobs>]] [<testset-directory>]

    -d          Display additional debugging information
    --dump-logs Print build log to STDOUT, if a build fails.
    -j [<jobs>] Run up to <jobs> jobs in parallel.
                If -j is passed without specifying <jobs>, the number
                of jobs started is <nproc>+1.
    -v          Be more verbose
    --help, -h  Print this help and exit

    The optional 3rd parameter causes runtests to only run tests that match
    the particular selection.  This parameter can be a list of selectors:
    what:<which>[,<what:...>]
END

    print encode_utf8($message);

    return;
}

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