#!/usr/bin/env perl

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

my $flag = $ARGV[0];
my $platform;
my $preset_platform;

if ($flag eq "" || $flag eq "--host") {
    $preset_platform=$ENV{'CHPL_HOST_PLATFORM'};
} elsif ($flag eq "--target") {
    $preset_platform=$ENV{'CHPL_TARGET_PLATFORM'};
    if ($preset_platform eq "") {
        $preset_platform=run("platform", "--host");
    }
}


if ($preset_platform eq "") {
    $platform = `uname -s`;
    chomp($platform);
    $platform = lc($platform);
    my $underscore = index($platform, "_");
    if ($underscore != -1) {
        substr($platform, $underscore) = "";
    }
    if ($platform eq "linux") {
        my $machine = `uname -m`;
        chomp($machine);
        if ($machine eq "x86_64") {
            my $build64_32 = $ENV{'CHPL_BUILD_X86_64_AS_32'};
            if ($build64_32 eq "1") {
                $platform = "linux64_32";
            } else {
                $platform = "linux64";
            }
        } else {
            $platform = "linux32";
        }
    }
} else {
    $platform = $preset_platform;
}

if ($platform eq "cray-cascade") {
    $platform = "cray-xc";

    if ($ARGV[1] eq 1) {
        warn "Warning: the 'cray-cascade' platform is deprecated.  Using 'cray-xc' instead."
    }
} 

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