#!/usr/bin/env perl
use strict;
use warnings;
use Fatal qw(open close);

use tool::Util qw(slurp numify_version);

use JSON;

my($input_file, $output_file) = @ARGV;

my $json = slurp($input_file);

my $meta = decode_json($json);

chmod 0666, $output_file if -e $output_file;

my $new_content = <<'EOT';
// THIS FILE IS AUTOMATICALLY GENERATED.
// DO NOT EDIT IT DIRECTLY. EDIT tool/make-meta INSTEAD.

final class Meta {
EOT

$new_content .= sprintf qq{    static const VERSION_STRING   = "%s";\n},
    $meta->{version};
$new_content .= sprintf qq{    static const VERSION_NUMBER   =  %g;\n},
    numify_version($meta->{version});
$new_content .= sprintf qq{    static const LAST_COMMIT_HASH = "%s";\n},
    `git log -n 1 --pretty=format:%H`;
$new_content .= sprintf qq{    static const LAST_COMMIT_DATE = "%s";\n},
    `git log -n 1 --pretty=format:%ci`; # ISO-8601 style date

$new_content .= <<'EOT';

    static const IDENTIFIER = Meta.VERSION_STRING + " (" + Meta.LAST_COMMIT_DATE + "; " + Meta.LAST_COMMIT_HASH + ")";
} // class Meta
EOT

if ($new_content ne (eval { slurp($output_file) } || "")) {
    open my($out), ">", $output_file;
    print $out $new_content;
    close $out;
}

