#! /usr/bin/env perl

use strict;
use warnings;

my $port = $ARGV[0];

# prepare frequently used regexes
my $trailing_comment      = qr{;(?>\s*)#(?>.*)};
my $leading_comment       = qr{(?:^|\n)(?>\s*)#(?>.*)};
my $connecting_backslash  = qr{\s*\\\n\s*};

my $quick_check = qr{:$port}io;
my $dependency  = qr{
                    (?=[plb])(?:port|(?:path|lib|bin):[^:]+)  # kind
                    :                                         # separator
                    (?i:$port)(\s|\n|$)                       # name
                  }xo;

$/ = ".\n";

while (defined(my $portfile = <*/*/Portfile>)) { 
  @ARGV = $portfile;

  while (<>) {
    # make a quick and dirty check if the port has a remote chance of
    # depending on $port
    if ( m{$quick_check} ) {

      s{$connecting_backslash}{ };    # merge backslash-connected lines
      s{$leading_comment}{};          # remove leading comments
      s{$trailing_comment}{};         # remove trailing comments

      if ( m{$dependency} ) {
        $portfile =~ s{/Portfile$}{}; # remove trailing '/Portfile'
        print "$portfile\n";
      }
    }
  }
}
