#!perl -w
use common::sense;

use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError);
# checksums
use Digest::SHA qw( sha512 );
use MIME::Base64 qw( encode_base64url );

my ( $ds, $os, $zs ) = ( 0, 0, 0 );
my $ofn = shift;
$ofn = "install/" . $ofn unless ($ofn =~ m:^install/:);
my $OFH = new IO::Uncompress::AnyUncompress $ofn
    or die "Cannot open $ofn for reading.\n\t$!";
my $zfn = $ofn;
$zfn =~ s:install/:install-zstd/:;
$zfn =~ s:\.xz$:.zst:;
#say STDOUT "$ofn => $zfn";
open my $ZFH, "|-", qw( /usr/bin/zstd --ultra -19 -fo ), $zfn;
binmode $ZFH;
select $ZFH;
while (<$OFH>) {
    s/^release: setup_current/release: setup-zstd/;
    if (m/^install:/) {
	my (undef, $fn, $fs, $sfn) = split;
	$fn =~ s:\.(xz|bz2)$:.zst:;
	$sfn = $fn;
	$sfn =~ s:^\.\.:install-zstd:;
	$sfn =~ s!^(?=(x86|x86_64|noarch)/)!install-zstd/!;
#	say STDOUT "$fn => $sfn";
	my @fs = stat $sfn;
	$os += $fs;
	$ds -= $fs - $fs[7];
	$fs  = $fs[7];
	$zs += $fs;
	my $sha512 = encode_base64url( Digest::SHA->new( "SHA-512" )->addfile( $sfn )->digest );
	say "install: $fn $fs $sha512";
    } else {
	print;
    }
}
select STDOUT;
say "Used $ds additional bytes: $os => $zs (", ((100.*$zs)/$os), "%) in $zfn.";
