#!/usr/bin/perl

=begin description

rename files in given directory hierarchy

=end

=cut

use v5.22;
use warnings;
use diagnostics;
use File::Basename;
use File::Find;
use File::Copy qw(move);
use File::Spec::Functions;
use Cwd qw(cwd);

my $directory = $ARGV[0];
my $extension = $ARGV[1];
my $subst_string = $ARGV[2];
my $string =  $ARGV[3] // "";
my @files_to_rename;

if (! defined $directory or ! defined $extension or
    ! defined $subst_string) {
    my $script_name = basename $0;
    say "Usage: \n\t$script_name directory extension subst_string [string]";
    exit;
}

sub wanted {
    if (-d "src/") {
        say "directory: $_";
    }
    if (m/(.+)\.$extension\z/) {
        my $filename = $1;
        my $new_filename = $filename =~ s/$subst_string/$string/rg;
        if ($new_filename ne $filename) {
            say "renaming ${filename}.${extension} -> ",
                "${new_filename}.${extension}";
            push @files_to_rename,
                [catfile(cwd, "${filename}.${extension}"),
                 catfile(cwd, "${new_filename}.${extension}")];
        }
    }
}

find(\&wanted, $ARGV[0]);
print('accept changes [y] or quit [q]: ');
my $line = <STDIN>;
chomp $line;
if ($line eq 'y' or $line eq '') {
    foreach my $tuple (@files_to_rename) {
        my $old = $tuple->[0];
        my $new = $tuple->[1];
        move $old, $new;
    }
} else {
    say 'changes not accepted';
    say 'quiting...';
}
