#!/usr/bin/perl -p

# This script adds an information icon to any link into /download/* - if there
# is more information to display than just the file name and size.

use autodie;

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

sub file {
    ($code, $lbl, $fn) = @_;
    my @info;
    push @info, sprintf '<em>PGP:</em> <a href="/download/%s.asc">%1$s.asc</a>', $fn if -e "$fn.asc";
    push @info, sprintf '<em>MD5:</em> <code>%s</code>', (slurp "$fn.md5") =~ /^([^ ]+)/ if -e "$fn.md5";
    push @info, sprintf '<em>SHA1:</em> <code>%s</code>', (slurp "$fn.sha1") =~ /^([^ ]+)/ if -e "$fn.sha1";
    push @info, sprintf '<em>SHA-256:</em> <code>%s</code>', (slurp "$fn.sha256") =~ /^([^ ]+)/ if -e "$fn.sha256";
    return $code if !@info;
    unshift @info, sprintf '<em>Size:</em> %s (%s bytes)', size(-s $fn), fullsize(-s $fn);
    unshift @info, sprintf '<em>File:</em> <a href="/download/%s">%1$s</a>', $fn;

    $id = sprintf 'fileinfo_%d', rand 1<<32;
    qq{<span class="fileinfo">}
    .   qq{<input id="$id" type="checkbox">}
    .   qq{<span>}
    .       qq{<label for="$id">close</label>}
    .       join('<br>', @info)
    .   qq{</span>}
    .   $code
    .   qq{ <label for="$id"><img src="/img/info.svg"></label>}
    .qq{</span>}
}

BEGIN { chdir 'pub/download' }
s{\[([^\]]+)\]\(/download/([^\) ]+)\)}{file $&,$1,$2}eg;
