#!/usr/bin/env perl
use warnings;
use strict;
use File::Find;
use File::Slurp;
use Module::Changes;
use Getopt::Attribute;
our $VERSION = '0.18';
our $version : Getopt(version|v=s);
our $version_from_changes : Getopt(changes|c);
our @dir : Getopt(dir|d=s);
die "can't specify both --version and --changes\n"
  if $version_from_changes && $version;
$version = get_version_from_changes() if $version_from_changes;
die '--version?' unless $version;
@dir = ('.') unless @dir;
find(
    sub {

        if (-d && $_ eq '.svn') {
            $File::Find::prune = 1;
            return;
        }
        return unless -f && -r;
        return if /\.swp$/;
        my $contents = read_file($_);
        if ($contents =~ s/(\$VERSION\s*=\s*([\'\"]))(.+?)\2/$1$version$2/) {
            printf "%s: set version %s\n", $File::Find::name, $version;
            open my $fh, '>', $_
              or die "can't open $File::Find::name for writing: $!\n";
            print $fh $contents;
            close $fh or die "can't close $File::Find::name: $!\n";
        }
    },
    grep {
        -d $_
      } @dir
);

sub get_version_from_changes {
    my $parser  = Module::Changes->make_object_for_type('parser_free');
    my $changes = $parser->parse_from_file('Changes');
    $changes->releases->[0]->version;
}
