#!/usr/bin/perl -w

#  Copyright (c) 2018-2023 Tobias Leupold <tl at stonemx dot de>
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#  1. Redistributions of source code must retain the above copyright notice, this
#     list of conditions and the following disclaimer.
#
#  2. Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions and the following disclaimer in the documentation
#     and/or other materials provided with the distribution.
#
#  3. Neither the name of the copyright holder nor the names of its contributors
#     may be used to endorse or promote products derived from this software without
#     specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


use strict;
use POSIX;
use File::Copy;

# ==================================================

# Adjust as needed :-)

# You can also create a file named "config.txt", with the following syntax:
#    variable = value
# (without any quotes)
#
# If present, it will be parsed and the following values will be overwritten.

my %config = (

# Output settings
'title'    => 'X. Muckturnier des Y-Vereins Z',
'subtitle' => 'am XX.XX.XXXX',
'tables'   => 16,

# Draw note template file
'drawNote' => 'draw_note.svg',

# Blank placeholder file
'blank'    => 'draw_note_placeholder.pdf',

# Output file
'outfile'  => 'Auslosungszettel.pdf',

# Adjustments needed by the printer
'offset'   => '0mm -3mm',
'delta'    => '0mm 3mm',

);

# ==================================================

# Parse the config file if it exists
my $configFile = './config.txt';
if (-e $configFile) {
    open my $fp, '<', $configFile;
    foreach my $line (<$fp>) {
        $line =~ s/^\s*|\s*$//;
        next if ! $line || $line =~ /^#/;
        $line =~ /\s*(.+?)\s*=\s*(.+)/;
        $config{$1} = $2;
    }
}

open my $in, '<', $config{'drawNote'};
local $/;
chomp(my $data = <$in>);
close $in;

my $note = 1;
my $firstNote = 1;
my $allPages = ceil($config{'tables'} / 8) * 2;
my $allNotes = $config{'tables'} * 2;

my $file = 0;
my @inFiles;

print "Generating draw notes ...\n";

for (my $page = 1; $page <= $allPages; $page++) {
    print "Generating notes on page $page/$allPages ";

    $note = $firstNote;
    for (my $i = 0; $i < 8; $i++) {
        my $out = sprintf('%04d.pdf', $file);
        push @inFiles, $out;

        my $table = floor(($note + 1) / 2);
        my $pair = $note % 2 eq 0 ? 2 : 1;

        if ($note > $allNotes) {
            copy($config{'blank'}, $out);
        } else {
            my $workData = $data;
            $workData =~ s/\@title\@/$config{'title'}/g;
            $workData =~ s/\@subtitle\@/$config{'subtitle'}/g;
            $workData =~ s/\@table\@/$table/g;
            if ($pair == 1) {
                $workData =~ s/\@pair\@/1 (bleibt sitzen)/g;
            } else {
                $workData =~ s/\@pair\@/2 (rückt weiter)/g;
            }
            open my $tmp, '>', 'tmp.svg';
            print $tmp $workData;
            close $tmp;
            system('inkscape', 'tmp.svg', '--export-filename=' . $out);
        }

        print ".";

        $note += $allPages;
        $file++;
    }

    print " " . ceil($page / $allPages * 100) . " % done\n";
    $firstNote++;
}

print "Compiling all generated notes ...\n";

system('pdfjam', '--nup', '2x4', '--clip', 'true', '--noautoscale', 'true',
       '--offset', $config{'offset'}, '--delta', $config{'delta'},
       '--outfile', $config{'outfile'}, @inFiles);

unlink 'tmp.svg';
unlink @inFiles;

print "done\n";
print "Wrote the compiled draw notes to $config{'outfile'}\n";
