#!/usr/bin/perl
#
# Copyright © 2005 Javier Fernandez-Sanguino Peña <jfs@computer.org>
# Copyright © 2005 Frank Lichtenheld <djpig@debian.org>
# Copyright © 2017-2025 Guillem Jover <guillem@debian.org>
#
# 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, see <https://www.gnu.org/licenses/>.
#

use strict;
use warnings;

use Dpkg::ErrorHandling;
use Dpkg::OpenPGP;
use Dpkg::OpenPGP::ErrorCodes;

# Verify that a .changes file has been OpenPGP signed and that the signatures
# are good.

my $file = shift;

# If the file is not found just exit with error.
exit 2 unless -r $file;

my $openpgp = Dpkg::OpenPGP->new(needs => { api => 'verify' });

exit 0 unless $openpgp->{backend}->has_verify_cmd();

print "Checking OpenPGP signatures on $file...\n";

my @certs;
push @certs, $openpgp->get_trusted_keyrings();
foreach my $host_keyring (split q{ }, $ENV{DUPLOAD_KEYRINGS} // q{}) {
    if (-r $host_keyring) {
        print "  Using keyring: $host_keyring\n";
        push @certs, $host_keyring;
    } else {
        print "  Skipping missing keyring: $host_keyring\n";
    }
}

if (@certs == 0) {
    error('no OpenPGP keyring specified or present for host %s',
          $ENV{DUPLOAD_HOST});
}

# Use the return code to determine whether the signature is fine.
my $rc = $openpgp->inline_verify($file, undef, @certs);
if ($rc) {
    error('cannot verify OpenPGP signature for %s: %s',
          $file, openpgp_errorcode_to_string($rc));
}

print "  Ok, OpenPGP signatures are valid.\n";

exit 0;
