#!/usr/bin/perl
use File::Fetch;
use File::Copy;
use File::Slurp;
use File::Basename;
use Cwd qw(abs_path getcwd);
use File::Path qw(make_path remove_tree);
use POSIX qw(strftime);
use Config;

if ( -d "source" ) {
    exit(0);
} else {
    print("configring casaviewer for building...\n");
}

#Fetch failed! HTTP response: 500 Internal Server Error [500 Can't verify SSL peers without knowing which Certificate Authorities to trust] at scripts/create-app line 62.
$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));
$java = '/usr/bin/java';
$jarfile_name = "create-app-assembly-1.12.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;

### install path
$distro_jarfile = $jarfile = "$path/java/$jarfile_name";
if ( ! -e $jarfile ) {
    ### development path
    $jarfile = "$path/../target/scala-2.12/$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 ( $Config{osname} eq "darwin" && ! -e "casaviewer.icns" ) {
    my $ff = File::Fetch->new(uri => "http://casa.nrao.edu/download/devel/xml-casa/viewer/casaviewer.icns");
    $ff->fetch( );
}

open(VER,"cd casa-source/casa5 && code/install/resolvegitrevision.sh --pretty-print 2>&1 |");
$major_ver = '';
$minor_ver = '';
$patch_ver = '';
$build_ver = '';
@lines = <VER>;
foreach ( @lines ) {
    if ( m|^(\d+)\.(\d+)\.(\d+)[^0-9]+(\d+)\+?$| ) {
        $major_ver = $1;
        $minor_ver = $2;
        $patch_ver = $3;
        $build_ver = $4;
        break;
    }
}
close(VER);
unless ( $major_ver ne '' && $minor_ver ne '' && $patch_ver ne '' && $build_ver ne '' ) {
    print "unable to determine version number from resolvegitrevision.sh output:\n";
    foreach ( @lines ) { print "    $_"; }
    die "cannot continue...";
}

#unless ( -e ".casacore-measures-patch-applied" ) {
#    my $patchfile = "scripts/waiting-on-casacore-acceptance.diff";
#    if ( -f $patchfile ) {
#        my $now_string = strftime("%a %b %e %H:%M:%S %Y",localtime);
#        open( TURD, "> .casacore-measures-patch-applied" );
#        print TURD "$now_string\n";
#        close(TURD);
#        open( PATCH, "patch -p0 < $patchfile |" );
#        while ( my $line = <PATCH> ) { print $line; }
#        close(PATCH);
#    }
#}

make_path("source");
open( VER_IN,  "< casa-source/casa5/code/stdcasa/version.cc.in" );
open( VER_OUT, "> source/casa-version.cc" );
while ( $_ = <VER_IN> ) {
    s|\@CASA_VERSION_MAJOR\@|$major_ver|g;
    s|\@CASA_VERSION_MINOR\@|$minor_ver|g;
    s|\@CASA_VERSION_PATCH\@|$patch_ver|g;
    s|\@CASA_VERSION_FEATURE\@|$build_ver|g;
    print VER_OUT $_;
}
close(VER_OUT);
close(VER_IN);
if ( ! -f "casa-source/casatools/casacore/casa/version.cc" ) {
    die "casacore version file (casa-source/casatools/casacore/casa/version.cc) does not exist...";
}
copy("casa-source/casatools/casacore/casa/version.cc","source/casacore-version.cc");
if ( -f "casa-source/casatools/casacore/casa/version.h.in" ) {
    my $casacore_major = "";
    my $casacore_minor = "";
    my $casacore_patch = "";
    open( CFG, "< casa-source/casatools/casacore/CMakeLists.txt" );
    while ( $_ = <CFG> ) {
        m|set\s*\(\s*PROJECT_VERSION_MAJOR\s+(\d+)\s*\)| && ($casacore_major = $1, next);
        m|set\s*\(\s*PROJECT_VERSION_MINOR\s+(\d+)\s*\)| && ($casacore_minor = $1, next);
        m|set\s*\(\s*PROJECT_VERSION_PATCH\s+(\d+)\s*\)| && ($casacore_patch = $1, next);
    }
    close(CFG);
    open( HIN, "<  casa-source/casatools/casacore/casa/version.h.in" );
    my @hin = <HIN>;
    close(HIN);
    open( HOUT, "> casa-source/casatools/casacore/casa/version.h" );
    foreach ( @hin ) {
        s|\@PROJECT_VERSION_MAJOR\@|$casacore_major|g;
        s|\@PROJECT_VERSION_MINOR\@|$casacore_minor|g;
        s|\@PROJECT_VERSION_PATCH\@|$casacore_patch|g;
        print HOUT $_;
    }
    close(HOUT);
}

make_path("include/casacore/casa");
make_path("include/casagrpc/protos");
open(CONFIG_H,"> include/casacore/casa/config.h");
print CONFIG_H casacore_config( );
close(CONFIG_H);


sub casacore_config {
    my $contents = <<'END-OF-STR';
#ifndef CASA_CONFIG_H
#define CASA_CONFIG_H
#define CASA_DEFAULT_ALIGNMENT (32UL)
#endif
END-OF-STR
    return $contents;
}