package App::GetClosestFile;

use strict;
use warnings;
use File::stat;
use Cwd;

# ABSTRACT: get full path matches for filename regexes in diretory trees

my $filename;
my @child_dirs = ();
my $show_all_matches = 0;
my $line_breaks = 0;

foreach my $arg (@ARGV) {
  if ($arg eq '--all') {
    $show_all_matches = 1;
  } elsif ($arg eq '--break') {
    $line_breaks = 1;
  } elsif ($arg eq '--help') {
    usage();
  } else {
    $filename = $arg;
  }
}


if (!$filename) {
  usage();
}

sub usage {
  print "\ngetclosest [options] filename

    options:

      --all       show all matches
      --break     print results on separate lines\n\n";

  exit;
}

sub read_dir {
  my $dir;
  my $dirname = shift;

  opendir($dir, $dirname) or die;

  my @files = readdir($dir);

  foreach my $file (@files) {
    if ($file eq "." or $file eq "..") {
      next;
    }

    stat($dirname . "/" . $file);

    if (-d _) {
      push @child_dirs, $dirname . "/" . $file;
    } else {
      if ($file =~ /$filename/) {
        print $dirname . "/" . $file;

        if ($show_all_matches == 1) {
          if ($line_breaks) {
            print "\n";
          } else {
            print " ";
          }
        } else {
          exit;
        }
      }
    }
  }
}

sub run {
  read_dir(getcwd);

  while (my $size = @child_dirs > 0) {
    my $dir = shift @child_dirs;
    read_dir($dir);
  }
}

1;

