#!/usr/bin/perl
use File::Basename;
use Cwd 'abs_path';
use Cwd 'getcwd';

BEGIN {
    ### move any directories specified with environment variables, e.g. PERL5LIB to the end
    #@INC = @lib::ORIG_INC;
    $ENV{PATH} = "/usr/bin:/bin:$ENV{PATH}";
    delete $ENV{IFS};
    delete $ENV{ifs};
    @INC = reverse(@INC);
    $HOME = $ENV{HOME};
};

$installpath = abs_path(dirname(abs_path($0)) . "/..");
$path        = normalize_path($installpath,$0);
$binary      = basename($path);
$ENV{'CASA_USE_CRASH_REPORTER'} = "true";
$ENV{'LC_NUMERIC'} = "en_US.UTF-8";
$ENV{'CASAPATH'} = "$installpath linux";
$ENV{'CASACORE_LDPATH'} = "$installpath/lib";
$ENV{'CASA_INSTALLATION_TYPE'} = "tar-installation";
if ( exists $ENV{'PYTHONPATH'} ) {
    $ENV{PYTHONPATH} = "$installpath/lib/python2.7:$installpath/lib/python2.7/site-packages:$ENV{PYTHONPATH}"
} else {
    $ENV{PYTHONPATH} = "$installpath/lib/python2.7:$installpath/lib/python2.7/site-packages"
}
$ENV{PATH} = "$installpath/lib/casa/bin:$ENV{PATH}";

## Wed Feb 17 10:29:37 EST 2016 after discussion with jkern
delete $ENV{LD_LIBRARY_PATH};
if ( exists $ENV{CASALD_LIBRARY_PATH} ) {
    $ENV{LD_LIBRARY_PATH} = $ENV{CASALD_LIBRARY_PATH}
}

## configure misc state for constituent packages...
$ENV{TCL_LIBRARY} = "$installpath/share/tcl";
$ENV{TK_LIBRARY} = "$installpath/share/tk";
$ENV{PGPLOT_FONT} = "$installpath/lib/pgplot/grfont.dat";
$ENV{PGPLOT_RGB} = "$installpath/lib/pgplot/rgb.txt";
$ENV{MATPLOTLIBRC} = "$installpath/share/matplotlib";
$ENV{QT_PLUGIN_PATH} = "$installpath/plugins";

if ( -x "$installpath/lib/casa/bin/$binary" ) {
    exec("$installpath/lib/casa/bin/$binary", @ARGV);
} else {
    print STDERR "$binary not found in $installpath/lib/casa/bin\n";
    exit(1);
}
exit(0);

sub normalize_path {
    my $divider = '/';
    my $root = shift(@_);        ## installation root
    my $path = shift(@_);        ## path to script ($0)

    sub normalize_worker {
        # clean path
        my @path = ( );
        foreach my $e (@_) {
            if ( $e eq '..' ) { pop(@path) }
            elsif ( $e ne '.' ) {
                my $path = join($divider,@path,$e);
                # encountered symlink and still outside of installation directory
                if ( -l $path && $path !~ m|^$root| ) {
                    my $linkpath = readlink($path); 
                    if ( substr($linkpath,0,1) eq $divider ) { 
                        # link to an absolute path. Need to clear up existing path. 
                        @path = ( ); 
                    } 
                    @path = normalize_worker(@path,split($divider,$linkpath)); 
                } else {
                    push(@path,$e);
                }
            }
        }

        # reconstruct path
        return @path;
    }

    # relative path
    if ( substr($path,0,1) ne $divider ) {
        $path = getcwd( ) . $divider . $path;
    }

    return join('/', normalize_worker( split($divider,$path) ) );
}
