#!/usr/bin/perl

# SPDX-License-Identifier: BSD-2-Clause
# Copyright © 2020 Nicholas Guriev <guriev-ns@ya.ru>

=head1 NAME

debian/uupdate - custom update wrapper

=head1 DESCRIPTION

uscan(1) calls to this short script after downloading a primary tarball from
GitHub.  In addition, the script downloads "test" directory using git(1),
verifies commit signature, and creates supplementary component tarball, skipping
"export-ignore" attribute. At the end, the script goes back to uupdate(1) for
these two tarballs.

It is impossible to apply untweaked uscan(1) because of incomplete upstream's
sources available at a release web-page. At the time of writing, uscan(1) can
not verify a Git commit (contrary to tags), it can not pack a specific folder,
and it can not override gitattributes(5).

=cut

use strict;
use warnings;
use autodie qw(:all);

use File::Temp qw(tempdir);
use Getopt::Long qw(:config pass_through);

GetOptions('upstream-version|v=s' => \my $version);
$version //= `dpkg-parsechangelog -SVersion` =~ s/-.*\n//r;

my $src_repo = 'https://github.com/dense-analysis/ale.git';
my $tmp_repo = tempdir(CLEANUP => 1);
my $tmp_arch = "$ENV{PWD}/../vim-ale_${version}.orig-test.tar";
local $ENV{GNUPGHOME} = tempdir(CLEANUP => 1);

sub execute {
	STDERR->say("+ @_") if $ENV{UUPDATE_TRACE};
	system @_;
}
sub redirect {
	my ($line, $mode, $file) = @_;
	STDERR->say("+ echo $line $mode $file") if $ENV{UUPDATE_TRACE};
	open my ($hd), $mode, $file;
	$hd->say($line);
	close $hd;
}

unless (-e "${tmp_arch}.xz") {
	execute 'gpg', '--import', 'debian/upstream/committer-key.asc';
	execute 'git', 'clone', '--bare', '--depth=1', "--branch=v${version}", $src_repo, $tmp_repo;
	execute 'git', '-C', $tmp_repo, 'verify-commit', 'HEAD';
	redirect '* -export-ignore', '>', "${tmp_repo}/info/attributes";
	execute 'git', '-C', $tmp_repo, 'archive', "--output=${tmp_arch}", 'HEAD', 'test';
	execute 'xz', $tmp_arch;
}

execute 'uupdate', '--find', "--upstream-version=${version}", @ARGV;
