#!/usr/bin/perl
# check an environment variable for existence and optionally check for a file in that path
# i.e. check_path.pl $LD_LIBRARY_PATH libSomething.o would check if all directories in LD_LIBRARY_PATH exist and if libSomething.o can be found in any of them.

use strict;

my $quiet = 0;
my $arg = shift;
#print "$arg\n";
if($arg eq "-q"){
    $quiet = 1;
    $arg = shift;
}

my @path = split(":",$arg);
my %locationhash;
foreach(@ARGV){
    $locationhash{$_} = [];
}

foreach my $pathentry (@path){
    next if($pathentry eq "");
    if(-f $pathentry){ 
        print "$pathentry found\n" unless $quiet;
    } elsif (-d $pathentry) {
        #        print "$pathentry found\n";
        foreach(@ARGV){
            if(-e $pathentry.'/'.$_){
                push(@{$locationhash{$_}}, $pathentry);
            }
        }
    } else {
        print "$pathentry does not exist!\n" unless $quiet;
    }
}

if($quiet){
    if($#{$locationhash{$ARGV[0]}} >= 0){
        print "@{$locationhash{$ARGV[0]}}[0]";
    } else {
        exit(1);
    }
} else {
    foreach(keys(%locationhash)){
        if($#{$locationhash{$_}} >= 0){
            print "$_:\n";
            my %hash = map { $_, 1 } @{$locationhash{$_}};
            foreach my $loc (keys(%hash)){
                print "\t$loc\n";
            }
        } else {
            print "$_ was not found in path.\n";
        }
    }
}
