#!/usr/bin/env perl

$VERBOSE = 0;
if (@ARGV > 2 && $ARGV[0] eq "-v") {
    $VERBOSE = 1;
    shift @ARGV;
}
if (@ARGV != 2) { die "USAGE: pscheckmods (module) (version)\n"; }

if ($VERBOSE) { print STDERR "checking in @INC\n"; }

## XXX EAM $realfilename = "ISO8601.pm";
## XXX EAM $result = do $realfilename;
## XXX EAM print "result: $result\n";
## XXX EAM print "$@\n";
## XXX EAM exit 2;

# &detailed_require ($ARGV[0]);

$x = eval "require $ARGV[0]; 1";
if (! $x) { 
    if (! $VERBOSE) { exit 1; }
    print "$ARGV[0]: missing\n";
    &detailed_require ($ARGV[0]);
}
if ($VERBOSE) { print "x: $x\n"; }

$version = eval "\$$ARGV[0]::VERSION";
print "$ARGV[0]: $version\n";

if ($ARGV[1] > $version) {
    print "$ARGV[0] is too old: have $version : need $ARGV[1]\n";
    exit 1;
}

exit 0;

sub detailed_require {
    my ($filename) = @_;
    $filename =~ s|::|/|g;
    $filename = "$filename.pm";
    # print "$filename\n";
    if (exists $INC{$filename}) {
	return 1 if $INC{$filename};
	die "Compilation failed in require";
    }
    my ($realfilename,$result);
  ITER: {
      foreach $prefix (@INC) {
	  $realfilename = "$prefix/$filename";
	  # print "real: $realfilename\n";
	  if (-f $realfilename) {
	      $INC{$filename} = $realfilename;
	      # print "calling 'do' on $realfilename\n";
	      $result = do $realfilename;
	      # print "result: $result\n";
	      # exit 4;
	      last ITER;
	  }
      }
      die "Can't find $filename in \@INC";
    }
    # print "here 1\n";
    if ($@) {
	# print "here 2\n";
	# print "$@";
	$INC{$filename} = undef;
	# print "here 2a\n";
	exit 2;
	die $@;
    } elsif (!$result) {
	# print "here 3\n";
	# print "no result\n";
	exit 2;
	delete $INC{$filename};
	die "$filename did not return true value";
    } else {
	# print "here 4\n";
	# print "done with detailed_require\n";
	exit 2;
	return $result;
    }
}
