#!/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'   => 10,
'rounds'   => 5,

# Score note template file
'infile'   => 'score_note.svg',

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

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

# Adjustments needed by the printer
'offset'   => '-1mm 1mm',
'delta'    => '5mm 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{'infile'};
local $/;
chomp(my $data = <$in>);
close $in;

my @inFiles;

my $page = 1;
my $firstOnPage;
my $table;
my $round;

my $allPages = ceil($config{'tables'} / 4) * $config{'rounds'};
my $i = 1;

for ($firstOnPage = 1; $firstOnPage <= $config{'tables'}; $firstOnPage += 4) {
    for ($round = 1; $round <= $config{'rounds'}; $round++) {
        print "Generating page $page/$allPages ";
        for ($table = $firstOnPage; $table <= $firstOnPage + 3; $table++) {
            my $out = sprintf('%04d.pdf', $i);
            push @inFiles, $out;
            if ($table > $config{'tables'}) {
                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;
                $workData =~ s/\@round\@/$round/g;
                open my $tmp, '>', 'tmp.svg';
                print $tmp $workData;
                close $tmp;
                system('inkscape', 'tmp.svg', '--export-filename=' . $out);
            }
            $i++;
            print ".";
        }
        print " " . ceil($page / $allPages * 100) . " % done\n";
        $page++;
    }
}

print "Compiling score notes ... ";

system('pdfjam', '--nup', '2x2', '--landscape', '--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 score notes to $config{'outfile'}\n";
