#!/usr/bin/perl -w

my $output = '../go-oo-team.png';
my $source = shift @ARGV || 'people.txt';
my $patch_path = shift @ARGV || "../../patches/dev300/go-oo-team.diff";

my %people;

my $sf;
open ($sf, $source) || die "Can't open $source: $!";
while (<$sf>) {
    /^#.*/ && next;
    /^\s*$/ && next;
    /\s*([^:]*)\s*:\s*(\S*)/ || next;
    $people{$1} = $2;
}
close ($sf);

my $montage = '';
my $text = '';
my $count = keys %people;
my $height = int (sqrt ($count));
my $width = int (($count + $height - 1) / $height);
my $i = 0;
for my $name ( sort keys %people ) {
    $montage .= "'$people{$name}' ";

    print "Name '$name'\n";
    my $firstname = $name;
    $firstname =~ s/ .*//;

    my $x = $i % $width;
    my $y = int ($i / $width);
    if ($x == 0) {
	$text .= "\\n" if ($y > 0);
	$text .= "$firstname";
    } else {
	$text .= ", $firstname";
    }
    $i++;
}

print "Generating image ...\n";
`montage -geometry +4+4 $montage $output` && die "Montage failed";
print "done.\n";

print "re-writing diff ...\n";
my $pf;
my @patch = ();
`cp -f $patch_path $patch_path.orig` && die "failed to backup $patch_path: $!";
open ($pf, $patch_path) || die "Can't open $patch_path: $!";
while (<$pf>) {
    my $line = $_;
    if ($line =~ m/^\+String STR_GO_OO_TEAM_NAMES/) {
	printf STDERR "Go go go !\n";
	push @patch, $line;           # + String ...
	$line = readline ($pf);       # +{ ...
	push @patch, $line;
	$line = readline ($pf);       # +    TEXT = " ...
	$line =~ s/TEXT = \".*[\r\n]*//;
	$line .= "TEXT = \"From top left: $text.\\n\";\n";
    }
    push @patch, $line;
}
close ($pf);

open ($pf, ">$patch_path.new") || die "Can't write to $patch_path.new: $!";
print $pf @patch;
close ($pf) || die "couldn't write $patch_path.new: $!";
`mv $patch_path.new $patch_path` && die "Failed to update patch";

print "update go-oo-team.diff with:\n\n";
print "TEXT = \"From top left: $text.\\n\";\n";
print "\n** Check:this image is $width x $height tiles\n\n";
`eog $output`;

