#!/usr/bin/env perl

use FindBin;
use lib $FindBin::Bin;
use Run qw(ret run);
use strict;

my $flag = $ARGV[0];
my $preset_compiler;
my $compiler;

if ($flag eq "" || $flag eq "--host") {
    $preset_compiler=$ENV{'CHPL_HOST_COMPILER'};
} elsif ($flag eq "--target") {
    $preset_compiler=$ENV{'CHPL_TARGET_COMPILER'};
}

if ($preset_compiler eq "") {
    my $platform = run("platform", $flag);
    # The cray platforms are a special case in that we want to "cross-compile"
    # by default. (the compiler is different between host and target, but the
    # platform is the same)
    if ($platform =~ /cray-(xc|xe|xk|xt)$/) {
        if ($flag eq "--host") {
            $compiler = "gnu";
        } else {
            my $subcompiler = "-$ENV{'PE_ENV'}";
            if ($subcompiler eq "-") {
                warn "WARNING: Compiling on $platform without a PrgEnv loaded";
                $subcompiler = "none";
            } else {
                $subcompiler =~ tr/A-Z/a-z/;
            }
            $compiler = "cray-prgenv$subcompiler";
        }
    } else {
        # Normal compilation (not "cross-compiling")
        # inherit the host compiler if the target compiler is not set and
        # the host and target platforms are the same
        if ($flag eq "--target") {
            if (run("platform", "--host") eq run("platform", "--target")) {
                $compiler=run("compiler", "--host");
            }
        } elsif ($platform eq "pwr5" || $platform eq "pwr6") {
            $compiler = "ibm";
        } elsif ($platform eq "marenostrum") {
            $compiler = "ibm";
        } elsif ($platform eq "darwin") {
            # default to clang on darwin if available
            my $clang_path = `which clang`;
            chomp($clang_path);
            if ($clang_path) {
                $compiler = "clang";
            } else {
                $compiler = "gnu";
            }
        } else {
            $compiler = "gnu";
        }
    }
} else {
    $compiler = $preset_compiler;
}

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