#!/usr/bin/perl

# Copyright 2022, gregor herrmann <gregoa@debian.org>
# Released under the same terms as Perl
#
# parts inspired by debian/tools/prepare-bpo.pl in fusioninventory-agent

use strict;
use warnings;
use Dpkg::Control::Info;
use Array::Utils qw(array_diff);
use Debian::PkgPerl::Util;
use 5.010;

my $control = Dpkg::Control::Info->new("debian/control");
my $source  = $control->get_source();

my $changed = 0;

foreach my $section (qw/Build-Depends Build-Depends-Indep/) {
    next unless $source->{$section};
    $source->{$section} =~ s/\s*\n//g;
    my @deps = split( /,/, $source->{$section} );

    my @depsFinal;
    foreach (@deps) {
        s/^\s*//;
        my $d            = $_;
        my @alternatives = split( /\s*\|\s*/, $d );
        my @alternativesFinal;
        foreach my $a (@alternatives) {
            ( my $pkgname ) = $a =~ /^(\S+)/;
            $a = "$a <!nocheck>"
                unless $a =~ /<!nocheck>$/
                or Debian::PkgPerl::Util->probable_build_dependency($pkgname);
            push @alternativesFinal, "$a";
        }
        push @depsFinal, join( " | ", @alternativesFinal );
    }
    $source->{$section} = join( ",\n", @depsFinal );
    $changed++ if array_diff( @deps, @depsFinal );
}

if ($changed) {
    open my $f, ">debian/control" or die "Can't open control file: $!\n";
    $control->output($f);
    close($f);
}

exit( !$changed );
