#!/usr/bin/perl

use v5.36;
use autodie;

say '---';
say 'title: Downloads';
say 'page-type: dl';
say '...';
say '';
say 'All PGP signatures are signed with my [personal key](https://yorhel.nl/key.asc) with fingerprint:<br>';
say '`7446 0D32 B808 10EB A9AF A2E9 6239 4C69 8C27 39FA`.';
say '';
say 'Checksums are also [committed into git](https://g.blicky.net/yorhel-dev.git/tree/pub/download).';
say '';

chdir 'pub/download';

sub slurp    { local $/=undef; open my $F, '<', shift; <$F> }
sub hash     { slurp(shift) =~ s/ .*$//sr }
sub fullsize { scalar reverse join ".", unpack "(A3)*", reverse shift }
sub size($s) { $s > 1<<20 ? sprintf '%.1f MiB', $s/(1<<20) : sprintf '%.1f KiB', $s/1024 }

# Attempt to get a more natural order,
sub expandNum { shift =~ s{([0-9]+(?:\.[0-9]+)*)}{ my $s = $1 =~ s/\.?([0-9]+)/sprintf '%07d', $1/erg; $s . ('0'x(50-length $s)) }erg =~ s/-/~/rg; }

for my $sha256 (sort { expandNum($a) cmp expandNum($b) } glob '*.sha256') {
    my $fn = $sha256 =~ s/\.sha256$//r;
    my $size = size -s $fn;
    my $fullsize = fullsize -s $fn;
    my $id = $fn =~ s/\./_/rg;

    say qq{<a id="$fn" href="/download/$fn">$fn</a> <a href="#$fn">🔗</a>};
    say ":   <table>";
    say "    <tr><td>Size  </td><td>$fullsize bytes ($size)</td></tr>";
    say '    <tr><td>MD5   </td><td>'.hash("$fn.md5").'</td></tr>';
    say '    <tr><td>SHA1  </td><td>'.hash("$fn.sha1").'</td></tr>';
    say '    <tr><td>SHA256</td><td>'.hash("$fn.sha256").'</td></tr>';
    say "    <tr><td>PGP   </td><td><a href=\"/download/$fn.asc\">asc</a></td></tr>";
    say '    </table>';
    say '';
}
