#!perl

# Note for Linux console users: this thing assumes UTF-8 support (so make sure
# you're running under a UTF-8 locale!), but you will also need a font that
# actually has all of the characters. Most console fonts do not support the
# half blocks, and will result in a diamond instead.
#
# At least on Debian, this one works:
#
#   setfont /usr/share/consolefonts/Uni2-VGA14.psf.gz
#
# To make this the default, run "dpkg-reconfigure console-setup", and pick:
# - "UTF-8"
# - "Combined - Latin; Slavic Cyrillic; Greek"
# - "VGA"
# - "8x14"
# and then reboot


use IPC::Open2 qw(open2);
use List::Util qw(sum);

my $iban = "NL99ABCD1234567890";
my $beneficiary = "Account Name";

sub hook_checkout($class, $cart, $user, $transaction_id, @) {
    my @entries = $cart->entries("is_deposit");

    my $amount = sum map $_->{amount}, grep $_->attribute('method') eq 'iban', @entries;

    if (defined $amount && $amount > 0) {
        my $pid = open2 my $out, my $in, qw(qrencode -t ansiutf8 -m 2)
            or die "Couldn't run qrencode";

        print $in join(
            "\n",
            "BCD", "002", 1, "SCT",
            "",
            $beneficiary,
            $iban,
            "EUR" . $amount,      # Amount
            "",
            "",
            "rb $user",
            "",
        );
        close $in;

        local $/ = "\n";
        my @lines = readline $out;
        close $out;

        waitpid($pid, 0);

        $lines[1] =~ s/$/ Note: ASN, Bunq, ING, and SNS are/;
        $lines[2] =~ s/$/ the only Dutch banks that support/;
        $lines[3] =~ s/$/ these EPC QR codes./;
        $lines[5] =~ s/$/ For manual transfers, use this/;
        $lines[6] =~ s/$/ IBAN: $iban/;

        print @lines;
    }
}