#!/usr/bin/env perl
use warnings;
use strict;
use File::Find;
use Getopt::Attribute;
our $prefix : Getopt(prefix|p=s);
our $suffix : Getopt(suffix|s=s);
our $join : Getopt(join|j=s);

sub projroot {
    my @projroot =
      map { s/^~/$ENV{HOME}/; $_ }
      split /\s*[:;]\s*/ => $ENV{PROJROOT};
    wantarray ? @projroot : \@projroot;
}

sub find_dists {
    my $restrict_path = shift;
    if (defined $restrict_path) {
        $restrict_path = [$restrict_path]
          unless ref $restrict_path eq 'ARRAY';
    } else {
        $restrict_path = [];
    }
    my %restrict_path = map { $_ => 1 } @$restrict_path;    # lookup hash
    my @distro;
    find(
        sub {
            return unless -d;

        # prune some things first for efficiency reasons - otherwise find() gets
        # quite slow.
            if (/^(\.svn|blib|skel)$/) {
                $File::Find::prune = 1;
                return;
            }
            if (-e "$_/Build.PL" || -e "$_/Makefile.PL" || -e "$_/dist.ini" ) {

              # only remember the distro if there was no path restriction, or if
              # it is within the restrict_path specs
                if (@$restrict_path == 0 || exists $restrict_path{$_}) {
                    push @distro => $File::Find::name;
                }

               # but prune anyway - we assume there are no distributions below a
               # directory that contains a Build.PL or a Makefile.PL.
                $File::Find::prune = 1;
            }
        },
        projroot()
    );
    wantarray ? @distro : \@distro;
}

# print one entry per line? disregard --join in that case
#
our $line_mode : Getopt(line|l);

# only print projroots, then exit -- no distfind
our $print_roots : Getopt(printroots);

# only print path to one or more given distributions
our @print_path : Getopt(printpath=s);

if ($print_roots) {
    print join ' ' => projroot();
    exit;
}
my @distro = find_dists(\@print_path);
$join   = ' ' unless defined $join;
$prefix = ''  unless defined $prefix;
$suffix = ''  unless defined $suffix;
@distro = map { "$prefix$_$suffix" } @distro;
if ($line_mode) {
    print "$_\n" for @distro;
} else {
    print join $join => @distro;
}
