#!/usr/bin/perl
use ExtUtils::MakeMaker;
use Getopt::Std;
use Config;
$ARCHNAME = $Config{archname};
use File::Basename;

getopts('e'); # embedding?

$CCFLAGS .= $ENV{CCFLAGS} if defined $ENV{CCFLAGS};

# $USE_KAFFE is a boolean that tells us whether or not we should use Kaffe.
# Set by find_includes (it seemed as good a place as any).

# Note that we don't check to see the version of Kaffe is one we support.
#  Currently, the only one we support is the one from CVS.

my $USE_KAFFE = 0;

#require "JNIConfig";

if ($^O eq 'solaris') {
    $LIBPATH = " -R$Config{archlib}/CORE -L$Config{archlib}/CORE";
} elsif ($^O eq 'MSWin32') {
    $LIBPATH = " -L$Config{archlib}\\CORE";
    # MSR - added MS VC++ default library path
    # bjepson - fixed to support path names w/spaces in them.
    push(@WINLIBS, (split"\;",$ENV{LIB}));
    grep s/\\$//, @WINLIBS; # eliminate trailing \
    grep s/\/$//, @WINLIBS; # eliminate trailing /
    $LIBPATH .= join(" ", "", map { qq["-L$_" ] } @WINLIBS);
} else {
    $LIBPATH = " -L$Config{archlib}/CORE";
}
#$LIBS = " -lperl";

# Figure out where Java might live
#
# MSR - added JDK 1.3
#

my @JAVA_HOME_GUESSES = qw(/usr/local/java /usr/java /usr/local/jdk117_v3
                         C:\\JDK1.1.8 C:\\JDK1.2.1 C:\\JDK1.2.2 C:\\JDK1.3 );

my @KAFFE_PREFIX_GUESSES = qw(/usr/local /usr);

if (! defined $ENV{JAVA_HOME}) {
        print "You didn't define JAVA_HOME, so I'm trying a few guesses.\n";
        print "If this fails, you might want to try setting JAVA_HOME and\n";
        print "running me again.\n";
} else {
        @JAVA_HOME_GUESSES = ( $ENV{JAVA_HOME} );
}

if (! defined $ENV{KAFFE_PREFIX}) {
        print "\nYou didn't define KAFFE_PREFIX, so I'm trying a few guesses.",
          "\nIf this fails, and you are using Kaffe, you might want to try\n",
          "setting KAFFE_PREFIX and running me again.\n",
          "If you want to ignore any possible Kaffe installation, set the\n",
          "KAFFE_PREFIX to and empty string.\n\n";
} else {
        @KAFFE_PREFIX_GUESSES = ($ENV{KAFFE_PREFIX} eq "") ? () :
                                                       ( $ENV{KAFFE_PREFIX} );
}

my(@KAFFE_INCLUDE_GUESSES, @KAFFE_LIB_GUESSES);
foreach my $kaffePrefix (@KAFFE_PREFIX_GUESSES) {
     push(@KAFFE_INCLUDE_GUESSES, "$kaffePrefix/include/kaffe");
     push(@KAFFE_LIB_GUESSES, "$kaffePrefix/lib");
     push(@KAFFE_LIB_GUESSES, "$kaffePrefix/lib/kaffe");
}
    $guess .= "/include/kaffe";

# Let's find out where jni.h lives
#
my @INCLUDE = find_includes();

if ($^O eq 'MSWin32') {
  # MSR - added MS VC++ default include path
  push(@INCLUDE,(split"\;",$ENV{INCLUDE}));
  grep s/\\$//, @INCLUDE; # remove trailing \
  grep s/\/$//, @INCLUDE; # remove trailing \
  $INC = join("", map { qq["-I$_" ] } @INCLUDE);

} else {
  $INC = join(" -I", ("", @INCLUDE));
}

# Let's find out the name of the Java shared library
#
my @JAVALIBS = find_libs();

# Find out some defines based on the library we are linking to
#
foreach (@JAVALIBS) {
    if ( $^O eq 'MSWin32') { # We're on Win32
        $INC =~ s#/#\\#g;
        $INC =~ s#\\$##;
	  print $INC, "\n";
        $CCFLAGS .= " -DWIN32 -Z7 -D_DEBUG";
        $MYEXTLIB = "$libjava";
      }
}

$CCFLAGS .= " -DKAFFE" if ($USE_KAFFE);

# Let's find out the path of the library we need to link against.
#
foreach (@JAVALIBS) {
    if ($^O eq 'MSWin32') { # We're on Win32
        $_ =~ s#/#\\\\#g;
    }
    my ($libname, $libpath, $libsuffix) = fileparse($_, ("\.so", "\.lib"));
    $libname =~ s/^lib//;
    if ($^O eq 'solaris') {
        $LIBPATH .= " -R$libpath -L$libpath"
    } else {
        $LIBPATH .= " -L$libpath"
    }
    $LIBS .= " -l$libname";
}

# Do we need -D_REENTRANT?
if ($LIBPATH =~ /native/) {
    print "Looks like native threads...\n";
    $CCFLAGS .= " -D_REENTRANT";
}

if ($opt_e) {
    print "We're embedding Perl in Java via libPerlInterpreter.so.\n";
    eval `../setvars -perl`;
    $CCFLAGS .= " -DEMBEDDEDPERL";
    $LIBPATH .= " -R$ENV{JPL_HOME}/lib/$ARCHNAME -L$ENV{JPL_HOME}/lib/$ARCHNAME";
    $LIBS    .= " -lPerlInterpreter";
}

# Needed for JNI.
if ($^O eq 'solaris') {
    $LIBS = " -lthread -lc $LIBS"; #-lthread must be first!!!
    $CCFLAGS .= " -D_REENTRANT";
}

# MSR - clean up LIBS
$LIBS =~ s/-l$//;

#
# Next, build JNI/Config.pm.  This is a superfluous thing for the SUN and
# Microsoft JDKs, but absolutely necessary for Kaffe.  I think at some
# point, the Microsoft and SUN implementations should use JNI::Config, too.
#

if (! -d "JNI") {
    mkdir("JNI", 0755) || die "Unable to make JNI directory: $!";
}
open(JNICONFIG, ">JNI/Config.pm") || die "Unable to open JNI/Config.pm: $!";

print JNICONFIG "# DO NOT EDIT!   Autogenerated by JNI/Makefile.PL\n\n",
                "package JNI::Config;\nuse strict;\nuse Carp;\n",
                "\nuse vars qw(\$KAFFE \$LIB_JAVA \$CLASS_HOME ",
                "\$LIB_HOME);\n\n",
                "\$KAFFE = $USE_KAFFE;\n\$LIB_JAVA = \"$JAVALIBS[0]\";\n";
if ($USE_KAFFE) {
  my $path = $JAVALIBS[0];
  $path =~ s%/(kaffe/)?libkaffevm.so$%%;

  print JNICONFIG "\$LIB_HOME = \"$path/kaffe\";\n";
  $path =~ s%/lib%%;
  print JNICONFIG "\$CLASS_HOME = \"$path/share/kaffe\";\n";
}
print JNICONFIG "\n\n1;\n";
close JNICONFIG;


my %Makefile = (
    NAME        => 'JNI',
    VERSION_FROM => 'JNI.pm',
    DEFINE        => '',
    LINKTYPE => 'dynamic',
    INC        => $INC,
    CCFLAGS => "$Config{ccflags} $CCFLAGS", 
    ($Config{archname} =~ /mswin32.*-object/i ? ('CAPI' => 'TRUE') : ()),

    clean => {FILES => "JNI/* JNI"}
);

$Makefile{LIBS} = ["$LIBPATH $LIBS"];
if ($MYEXTLIB) {
    $Makefile{MYEXTLIB} = $MYEXTLIB;
}

# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
#
WriteMakefile(%Makefile);

if ($USE_KAFFE) {
  my $path = $JAVALIBS[0];
  $path =~ s%/libkaffevm.so$%%;
  print "\n\n***NOTE: be sure to have:\n",
            "              LD_LIBRARY_PATH=$path\n",
            "         in your enviornment (or installed as a system dynamic\n",
            "         library location) when you compile and run this.\n";
}

# subroutine to find a library
#
sub find_stuff {

    my ($candidates, $locations) = @_;
    my $lib;
    $wanted = sub {
        foreach my $name (@$candidates) {
            if (/$name$/ and ! /green_threads/ and !/include-old/) {
                    $lib = $File::Find::name;
            }
        }
    };
    
    use File::Find;
    foreach my $guess (@$locations) {
        next unless -d $guess;
        find (\&$wanted, $guess);
    }
    if (! $lib) {
        print "Could not find @$candidates\n";
    } else {
        print "Found @$candidates as $lib\n\n";
    }
    return $lib;
}

# Extra lib for Java 1.2
#
#  if we want KAFFE, check for it, otherwise search for Java

sub find_libs {
  my($libjava, $libawt, $libjvm);

  if ($USE_KAFFE) {
    $libjava = find_stuff(['libkaffevm.so'], \@KAFFE_LIB_GUESSES);
    $libawt = find_stuff(['libawt.so'], \@KAFFE_LIB_GUESSES);
  } else {
    $libjava = find_stuff(['libjava.so', 'javai.lib', 'jvm.lib'],
                             \@JAVA_HOME_GUESSES);
    $libjvm  = find_stuff(['libjvm.so'],  \@JAVA_HOME_GUESSES);
    $libawt  = find_stuff(['libawt.so'], \@JAVA_HOME_GUESSES);
    if (defined $libjvm) { # JDK 1.2
      my $libhpi  = find_stuff(['libhpi.so'], \@JAVA_HOME_GUESSES);
      return($libjava, $libjvm, $libhpi, $libawt);
    }
  }
  return($libjava, $libawt);
}

# We need to find jni.h and jni_md.h
#

# Always do find_includes as the first operation, as it has the side effect
# of deciding whether or not we are looking for Kaffe.  --bkuhn

sub find_includes {

  my @CANDIDATES = qw(jni.h jni_md.h);
  my @includes;

  sub find_inc {
    foreach my $name (@CANDIDATES) {
      if (/$name$/) {
	my ($hname, $hpath, $hsuffix) = 
	  fileparse($File::Find::name, ("\.h", "\.H"));
	unless ($hpath =~ /include-old/) {
	  print "Found $hname$hsuffix in $hpath\n";
	  push @includes, $hpath;
	} 
      }
    }
  }
    
  use File::Find;
  foreach my $guess (@KAFFE_INCLUDE_GUESSES) {
    next unless -d $guess;
    find (\&find_inc, $guess);
  }
  # If we have found includes, then we are using Kaffe.
  if (@includes > 0) {
    $USE_KAFFE = 1;
  } else {
    foreach my $guess (@JAVA_HOME_GUESSES) {
      next unless -d $guess;
      find (\&find_inc, $guess);
    }
  }
  die "Could not find Java includes!" unless (@includes);

  return @includes;
}

