#!/usr/bin/perl
use warnings;
use strict;

use Text::CSV;
use Data::Dump qw(dump);
use autodie;

my ( $svg_template, $csv_file ) = @ARGV;

die "usage: $0 template.svg data.csv\n" unless -r $svg_template && -r $csv_file;

my $svg;
{
	local $/ = undef;
	open(my $fh, '<:encoding(utf8)', $svg_template);
	$svg = <$fh>;
	close $fh;
}

my $vars;

my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
	or die "Cannot use CSV: ".Text::CSV->error_diag ();

my $nr = 1;

open(my $inkscape, '|-', 'inkscape --shell --without-gui');

open my $fh, "<:encoding(utf8)", $csv_file or die "$csv_file: $!";
while ( my $row = $csv->getline( $fh ) ) {
	if ( ! $vars ) { # header row
		my $col = 0;
		$vars->{ '%VAR_' . $_ . '%' } = $col++ foreach @$row;
		warn "variables ",dump $vars;
		next;
	} else {
		my $new_svg = $svg;
		foreach my $pattern ( keys %$vars ) {
			$new_svg =~ s/\Q$pattern\E/$row->[$vars->{$pattern}]/sgx ||
				warn "didn't find $pattern in $svg_template";
		}
		my $tmp_path = sprintf "/tmp/%s-%04d", $svg_template, $nr++;
		open(my $fh, '>', "$tmp_path.svg");
		print $fh $new_svg;
		close $fh;

		print $inkscape "$tmp_path.svg --export-area-page --export-pdf $tmp_path.pdf\n";

		warn "# $_ ", -s $_, " bytes\n" foreach glob "$tmp_path.*";
	}
}
$csv->eof or $csv->error_diag();
close $fh;

close $inkscape;

warn "generated $nr files in /tmp/$svg_template-*.pdf\n";

my $print_pdf = 'nup.pdf';

system "pdfnup --suffix nup --nup '2x5' --paper a4paper --no-landscape --scale 1.0 --frame true --noautoscale true --outfile $print_pdf -- /tmp/$svg_template-*.pdf";

warn "PRINT file: $print_pdf ", -s $print_pdf, " bytes\n";
