#!/usr/bin/perl
use Mojo::Base -strict;
use open qw( :std :encoding(UTF-8) );

my $source_package;
if (defined $ARGV[0]) {
    $source_package = $ARGV[0];
} else {
    $source_package = `dpkg-parsechangelog -S Source`;
    chomp $source_package;
}
die "ERROR: invalid source package name ('$source_package')\nUsage: $0 [openqa-server|openqa]\n"
  unless ("$source_package" =~ /^openqa(-server)?$/);

sub is_server() { return ('openqa-server' eq $source_package); }

open(my $fh, '<', 'debian/control.in') || die "ERROR: failed to open control.in $?";

print <<'EOF';
# =-=-=-=-= DO NOT EDIT THIS FILE DIRECTLY =-=-=-=-=-=
# It is generated by debian/generate-control.pl from debian/control.in
# See debian/source/README.source for more details.
# =-=-=-=-= DO NOT EDIT THIS FILE DIRECTLY =-=-=-=-=-=
EOF

while (<$fh>) {
    chomp;
    next if is_server ? (/#%C%#/) : (/#%S%#/);
    s/\s*#%[SC]%#\s*$//;
    if (/#%(SERVER|CLIENT)_SECTION_START%#/) {
        my $marker = "$1";
        my $current_mark = is_server ? 'SERVER' : 'CLIENT';
        if ("$current_mark" ne "$marker") {
            while (<$fh>) {
                last if (/#%${marker}_SECTION_END%#/)
            }
        }
        next;
    }
    next if /#%(CLIENT|SERVER)_SECTION_END%#/;
    s/#%SOURCE_PACKAGE%#/$source_package/;
    say;
}
