#!/usr/bin/env perl

#use FindBin;
#use lib $FindBin::Bin;

use File::Basename;
use lib (dirname(__FILE__));
use Run qw(ret run);
use strict;

my $preset_atomics         = $ENV{'CHPL_ATOMICS'};
my $preset_network_atomics = $ENV{'CHPL_NETWORK_ATOMICS'};

my $flag = $ARGV[0];

my $atomics;

my $network_atomics = 0;
if ($flag eq "--network") {
    $network_atomics = 1;
}

if ($network_atomics == 1) {
    if ($preset_network_atomics eq "") {
        my $comm = run("comm");
        if ($comm eq "ugni") {
            $atomics = $comm;
        } else {
            $atomics = "none";
        }
    } else {
        $atomics = $preset_network_atomics;
    }
} elsif ($preset_atomics eq "") {

    my $compiler = run("compiler", "--target");
    my $platform = run("platform", "--target");

    #
    # we currently support intrinsics for 64 bit platforms using gcc, intel,
    # or cray compilers but not pgi. pgi does not have support for atomic
    # intrinsics so we revert to locks for that case. We could add support for
    # 32-bit platforms and only use locks for 64-bit atomics but we can cross
    # that bridge when we get there. 
    if ($platform eq "linux32") {
        $atomics = "locks";
    } elsif ($compiler eq "gnu" || $compiler eq "cray-prgenv-gnu") {
        # Check the compiler version
        my $version = `gcc -dumpversion`;
        my @vers = split(/\./, $version);
        if( ($vers[0] == 4 && $vers[1] >= 1) || $vers[0] > 4 ) {
            $atomics = "intrinsics";
        } else {
            $atomics = "locks";
        }
    } elsif ($compiler eq "intel" || $compiler eq "cray-prgenv-intel") {
        $atomics = "intrinsics";
    } elsif ($compiler eq "cray" || $compiler eq "cray-prgenv-cray") {
        $atomics = "intrinsics";
    } elsif ($compiler eq "clang") {
        $atomics = "intrinsics";
    } else {
        $atomics = "locks";
    }
} else {
    $atomics = $preset_atomics;
}

ret($atomics);
print "$atomics\n" unless caller;
