#!/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);
    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";
        }
    } elsif ($platform eq "pwr5" || $platform eq "pwr6") {
	$compiler = "ibm";
    } elsif ($platform eq "marenostrum") {
	$compiler = "ibm";
    } else {
	if (run("platform", "--host") eq run("platform", "--target")) {
	    $compiler=$ENV{'CHPL_HOST_COMPILER'};
	}
	if ($compiler eq "") {
	    $compiler = "gnu";
	}
    }
} else {
    $compiler = $preset_compiler;
}

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