package WhichHash;

require Exporter;

@ISA = qw(Exporter);
@EXPORT_OK = qw( init_which );

use strict;

sub add_dir($@)
{
  my $result = shift;

  for my $dir(@_)
  {
    opendir(DIR, $dir) || next;
    for my $name(readdir(DIR))
    {
      next if defined($$result{$name});
      my $file = $dir . '/' . $name;
      stat($file) || next;
      next if -d $file;
      next unless -x $file;
      $$result{$name} = $file;
    }
    closedir DIR;
  }
}

sub add_var($$)
{
  my $result = shift;
  my $varname = shift;

  my $path = $ENV{$varname};
  return "Environment variable $varname not defined." if (!defined($path));
  for my $dir(split(/:/, $path))
  {
    add_dir($result, $dir);
  }
  return undef;
}

sub init_which($)
{
  my $result = shift;

  # On SunOS 5.6 the POSIX confirming variations are in /usr/xpg4/bin
  # and /bin is a link to /usr/bin. Since packages are installed into
  # /usr/bin pkgchk will not find files in /bin
  add_dir $result, '/usr/xpg4/bin', '/usr/bin';

  return add_var $result, 'PATH';
}

1;
