#!/usr/bin/perl -w

use warnings;
use strict;

use File::Basename;
use File::Copy;

my $recurse = 1;
my $regexp = undef;
my $justmatch = 0;

sub find_match {
    my $fname = shift;
    my $dname = shift;

    opendir(DIRH, $dname) || die("Couldn't open directory [$dname]: $!");
    my @dirfiles = readdir(DIRH);
    closedir(DIRH);

    $fname = lc($fname);
    foreach (@dirfiles) {
        return $_ if ($fname eq lc($_));
    }

    return undef;  # new on left.
}


sub check_file {
    my $origfile = shift;
    my $compfile = shift;

    #print("check_file: $origfile, $compfile\n");

    return if ((defined $regexp) and (basename($origfile) !~ /$regexp/));
    print("$origfile matches.\n"), return if ($justmatch);

    my $base = basename($origfile);
    my $compdir = dirname($compfile);
    my $pair = find_match($base, $compdir);
    if (defined $pair) {  # file exists on both sides.
        if ($base ne $pair) {
            my $newfile = dirname($origfile) . '/' . $pair;
            print("renaming [$origfile] to [$newfile].\n");
            move($origfile, $newfile) || die("move() failed: $!\n");;
            $origfile = $newfile;
            $compfile = $compdir . '/' . $pair;
        }
    
        # Check subdirs...
        if (($recurse) and (-d $origfile)) {
            opendir(DIRH, $origfile) || die("Couldn't open directory [$origfile]: $!");
            my @dirfiles = readdir(DIRH);
            closedir(DIRH);
            #print("$origfile must check @dirfiles\n");
            foreach (@dirfiles) {
                next if (($_ eq ".") || ($_ eq ".."));
                check_file($origfile . '/' . $_, $compfile . '/' . $_);
            }
        }
    }

    #print("check_file returns\n");
}


# Mainline ...

my $arg1 = undef;
my $arg2 = undef;

foreach (@ARGV) {
    if ($_ eq '--recurse') {
        $recurse = 1;
        next;
    }

    if ($_ eq '--no-recurse') {
        $recurse = 0;
        next;
    }

    if ($_ eq '--match-and-exit') {
        $justmatch = 1;
        next;
    }

    if ($_ eq '--no-match-and-exit') {
        $justmatch = 0;
        next;
    }

    if (s/^--regexp=(.*)/$1/) {
        $regexp = $_;
        #print("Regexp is [$regexp].\n");
        next;
    }

    $arg1 = $_, next if not defined $arg1;
    $arg2 = $_, next if not defined $arg2;
    die("too many or unknown arguments.\n");
}

die("not enough arguments.\n") if (not defined $arg1) or (not defined $arg2);
die("arg1 is not a dir.\n") if (not -d $arg1);
die("arg2 is not a dir.\n") if (not -d $arg2);
check_file($arg1, $arg2);
exit 0;

# end of fncorrect.pl ...

