#!/usr/bin/perl

###
### usage:   mod-closure <PATH-TO-MODULE> ...
###
### e.g.     mod-closure build/lib.macosx-10.12-x86_64-3.6/casatools
###

use File::Fetch;
use File::Basename;
use Cwd qw(abs_path getcwd);
use File::Path qw(make_path remove_tree);

###
### avoid: "Fetch failed! HTTP response: 500 Internal Server Error [500 Can’t verify SSL peers without knowing which Certificate Authorities to trust]"
###
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
###
### avoid: TLSv1.0 backends...
###
$File::Fetch::BLACKLIST = [qw|lwp httptiny httplite|];

$exe = abs_path($0);
$path = abs_path(dirname($exe));
chop($java=`which java`);
$jarfile_name = "mod-closure-assembly-1.11.jar";
@java_version = ( );
open(JAVAVER, "$java -version 2>&1 |");
foreach ( <JAVAVER> ) {
    if ( m|version "?(\d+)\.(\d+)|i ) {
        @java_version = ($1,$2);
        #print "found java version ", join('.',@java_version), "\n";
    }
}
close(JAVAVER);
die "cannot run $java" unless scalar(@java_version) > 0;
die "java version 1.8 or greater is required\n" unless ($java_version[0] == 1 && $java_version[1] >= 8) or $java_version[0]>=10;

### install path
$distro_jarfile = $jarfile = "$path/java/$jarfile_name";

if ( ! -e $jarfile ) {
    $jarfile = $distro_jarfile;
    ### pull from download url
    my $jardir = dirname($jarfile);
    make_path($jardir);
    my $ff = File::Fetch->new(uri => 'http://casa.nrao.edu/download/devel/xml-casa/java/' . $jarfile_name);
    my $where = $ff->fetch( to => $jardir );
}
die "configuration error, cannot find jar file ($jarfile_name)" unless -e $jarfile;

if ( $^O ne "linux" ) {
    unshift( @ARGV, 'exclude=/usr/lib' );
}
unshift( @ARGV, basename($java), '-jar', $jarfile );
exec { $java } @ARGV;