#!/usr/bin/env perl

use strict;
use warnings;
use utf8;

use POSIX 'getcwd';
use JSON::PP 'decode_json';

sub cat {
    my $file = shift;
    local $/;
    my $f;
    open( $f, '<', $file ) or die "Cannot open '$file': $!\n";
    my $output = readline($f);
    close($f);
    return $output;
}

my $mfile = $ARGV[0];
exit 0
  unless $mfile
  and $mfile =~ m/^blib.*\.pm$/s
  and -f $mfile
  and -f 'META.json';

my $version = decode_json( cat('META.json') )->{version};
die "Version not found in META\n" unless $version;
$version =~ s/^v//;
die "Invalid version string '$version'\n" unless $version =~ m/^[0-9.]+$/s;

my $module = cat($mfile);
$module =~ s/^
    (package\s+([a-z0-9_:]+)\s*;\s*\n+use.*?\n\n)
    /$1\$$2::VERSION = '$version';\n\n/isx;
my $f;
chmod( 0644, $mfile );
open( $f, '>', $mfile ) or die "Cannot open '$mfile': $!\n";
print( $f $module );
close($f);
chmod( 0444, $mfile );
