#!/usr/bin/perl
#
# Turn debian/<package>.alternatives into update-alternatives(1) calls in the
# maintainer scripts of <package>.
#
# dh_installalternatives(1) is the helper that normally does this, but it only
# exists since debhelper 13.  The build environment only provides debhelper 12,
# where debian/*.alternatives are silently ignored: the binary packages are
# built without any update-alternatives call in their postinst/prerm, so
# /usr/bin/vim, /usr/bin/vi, /usr/bin/editor, ... are never created.
#
# This script mimics dh_installalternatives: it appends the postinst snippets
# to (and prepends the prerm snippets to) debian/<package>.postinst.debhelper
# and debian/<package>.prerm.debhelper, from where dh_installdeb(1) merges
# them into the maintainer scripts.  It has to run after the packages have
# been installed into debian/<package>/ and before dh_installdeb.  The
# snippets are the same ones dh_installalternatives generates.
#
# The format of debian/<package>.alternatives is the one documented in
# dh_installalternatives(1).  Like dh_installalternatives, this script puts
# the values into the maintainer scripts without any quoting, so it rejects
# everything but plain names, paths and integers instead.
#
# debian/rules only runs this script for the architecture dependent packages,
# so it refuses the alternatives of an "Architecture: all" package rather than
# silently ignoring them.
#
# This can go away together with the override_dh_installalternatives and
# override_dh_installdeb-arch targets in debian/rules once the package is
# built with debhelper >= 13.

use strict;
use warnings;
use Dpkg::Control::Info;

my $TOOL = 'debian/gen-alternatives';
my $BEGIN = "# Automatically added by $TOOL\n";
my $END = "# End automatically added section\n";
my $CONT = " \\\n            ";    # line continuation, as in debhelper

my %FIELDS = map { $_ => 1 } qw(name link alternative priority dependents);

# Nothing in here is special to the shell or can be mistaken for an option.
my $PLAIN = qr{\A[A-Za-z0-9._+/][A-Za-z0-9._+/-]*\z};
my $INTEGER = qr{\A-?[0-9]+\z};

sub fail
{
    print STDERR "$TOOL: error: @_\n";
    exit 1;
}

sub slurp
{
    my ($file) = @_;

    return '' if !-e $file;
    open(my $fh, '<', $file) or fail("cannot read $file: $!");
    local $/ = undef;
    my $content = <$fh>;
    close($fh);
    return $content;
}

# Replace the file in one step, so that a failure never leaves a truncated
# file behind.
sub spew
{
    my ($file, $content) = @_;
    my $tmp = "$file.tmp$$";

    open(my $fh, '>', $tmp) or fail("cannot write $tmp: $!");
    my $ok = print({$fh} $content);
    $ok = close($fh) && $ok;
    $ok = rename($tmp, $file) if $ok;
    if (!$ok) {
        my $err = "$!";
        unlink($tmp);
        fail("cannot write $file: $err");
    }
}

# Parse a deb822-like file into a list of {lowercased field => value}.
sub parse_alternatives
{
    my ($file) = @_;
    my (@stanzas, %cur, $field);

    open(my $fh, '<', $file) or fail("cannot open $file: $!");
    while (my $line = <$fh>) {
        chomp($line);
        next if $line =~ /^#/;
        if ($line =~ /^\s*$/) {
            push(@stanzas, {%cur}) if %cur;
            %cur = ();
            undef $field;
        } elsif ($line =~ /^\s/) {
            fail("$file:$.: continuation line outside of a field")
                if !defined($field);
            $cur{$field} .= "\n$line";
        } elsif ($line =~ /^([A-Za-z-]+):\s*(.*?)\s*$/) {
            $field = lc($1);
            fail("$file:$.: unknown field \"$1\"") if !$FIELDS{$field};
            $cur{$field} = $2;
        } else {
            fail("$file:$.: cannot parse \"$line\"");
        }
    }
    close($fh);
    push(@stanzas, {%cur}) if %cur;
    return @stanzas;
}

sub check_plain
{
    my ($value, $what, $file) = @_;

    fail("invalid value \"$value\" for $what in $file: only letters, digits "
        . "and . _ + / - are allowed, and no leading \"-\"")
        if $value !~ $PLAIN;
}

# Return the postinst and the prerm snippet for one stanza.
sub snippets
{
    my ($pkg, $file, $st) = @_;

    for my $f (qw(name link alternative priority)) {
        fail("missing mandatory \"$f\" field in $file")
            if !defined($st->{$f}) || $st->{$f} eq '';
    }
    my ($name, $link, $alt, $prio) = @{$st}{qw(name link alternative priority)};

    check_plain($name, 'Name', $file);
    check_plain($link, "Link of \"$name\"", $file);
    check_plain($alt, "Alternative of \"$name\"", $file);
    fail("invalid Priority \"$prio\" of \"$name\" in $file: not an integer")
        if $prio !~ $INTEGER;

    fail("invalid name \"$name\" in $file: must not contain a slash")
        if index($name, '/') >= 0;
    fail("\"$name\" in $file: name and alternative are identical")
        if $name eq $alt;
    # Same sanity check as dh_installalternatives: a typo or a failed
    # dh_install must not end up as a dangling alternative.
    fail("alternative \"$alt\" for \"$name\" in $file does not exist in debian/$pkg")
        if !-e "debian/$pkg$alt" && !-l "debian/$pkg$alt";
    fail("alternative \"$alt\" for \"$name\" in $file is a directory")
        if -d "debian/$pkg$alt";

    my @slaves;
    if (defined($st->{dependents})) {
        my %seen;
        for my $line (split(/\n/, $st->{dependents})) {
            my @f = split(' ', $line);
            next if !@f;
            fail("dependent \"$line\" of \"$name\" in $file must consist of "
                . "exactly 3 space-separated values")
                if @f != 3;
            check_plain($_, "Dependents of \"$name\"", $file) for @f;
            fail("invalid dependent name \"$f[1]\" of \"$name\" in $file")
                if index($f[1], '/') >= 0 || $f[1] eq $f[2];
            fail("dependent \"$f[1]\" of \"$name\" in $file is listed twice")
                if $seen{$f[1]}++;
            push(@slaves, "--slave @f");
        }
        fail("empty Dependents field for \"$name\" in $file") if !@slaves;
    }

    my $install = "--install $link $name $alt $prio";
    $install .= $CONT . join($CONT, @slaves) if @slaves;

    my $postinst = 'if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ]'
        . ' || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ]; then' . "\n"
        . "        update-alternatives $install\n"
        . "fi\n";
    my $prerm = 'if [ "$1" = "remove" ]; then' . "\n"
        . "\tupdate-alternatives --remove $name $alt\n"
        . "fi\n";
    return ($postinst, $prerm);
}

# The packages debian/rules does not run this script for.
my %indep;
for my $p (Dpkg::Control::Info->new('debian/control')->get_packages()) {
    $indep{$p->{Package}} = 1 if ($p->{Architecture} // '') eq 'all';
}

# Parse, check and generate everything first and write only when all of it
# went well, so that an error never leaves some of the files modified.
my (%new, @summary);
my $found = 0;
for my $file (sort glob('debian/*.alternatives')) {
    my ($pkg) = $file =~ m{^debian/(.+)\.alternatives$} or next;

    fail("$file: $pkg is \"Architecture: all\", but debian/rules only runs "
        . "$TOOL for the architecture dependent packages")
        if $indep{$pkg};

    # Not being built in this run (e.g. dpkg-buildpackage -A).
    next if !-d "debian/$pkg";
    $found++;

    my $postinst_file = "debian/$pkg.postinst.debhelper";
    my $prerm_file = "debian/$pkg.prerm.debhelper";
    my $postinst = slurp($postinst_file);
    my $prerm = slurp($prerm_file);

    # debhelper's dh_prep removes the *.debhelper files, so this only
    # triggers if we are called twice in one run.
    next if index($postinst, $BEGIN) >= 0 || index($prerm, $BEGIN) >= 0;

    my @stanzas = parse_alternatives($file);
    fail("no alternatives found in $file") if !@stanzas;

    my ($new_postinst, $new_prerm) = ('', '');
    for my $st (@stanzas) {
        my ($i, $r) = snippets($pkg, $file, $st);
        $new_postinst .= $BEGIN . $i . $END;
        # Like for dh_installalternatives, prerm snippets run in reverse
        # order.
        $new_prerm = $BEGIN . $r . $END . $new_prerm;
    }

    $new{$postinst_file} = $postinst . $new_postinst;
    $new{$prerm_file} = $new_prerm . $prerm;
    push(@summary, [$pkg, scalar(@stanzas)]);
}

# Silently producing packages without alternatives is the very bug this
# script exists for, so complain loudly if there was nothing to do.
fail("no package with a debian/*.alternatives file found in debian/")
    if !$found;

spew($_, $new{$_}) for sort keys %new;
printf("%s: %s: %d alternatives added to postinst and prerm\n", $TOOL, @{$_})
    for @summary;
