#  Copyright (c) 1997-2015
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
#  http://www.polymake.org
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------

sub platform_name {
   my $platform;
   if ($^O !~ /aix|rs6000|ibm/i) {
      ($platform)= `uname -p` =~ /(\w+)/;
      if ($platform eq "unknown") {
         ($platform)= `uname -m` =~ /(\w+)/;
      }
   }
   $platform || $Config{archname};
}

sub locate_build_dir {
   my $top= @_>0 && "$_[0]/";
   my $arch;
   if ($arch=$ENV{Arch}) {
      if ($^O eq "darwin" && $arch !~ /^darwin\./) {
         $arch="darwin.$arch";
      }
      -d "${top}build.$arch"
         or die "directory ${top}build.$arch does not exist;\n",
                "Please check the spelling of the Arch argument or run ${top}configure --build=$arch.\n";
   } elsif ($^O ne "darwin") {
      $arch=platform_name();
      unless (-d "${top}build.$arch") {
         if (glob "${top}build.*") {
            die "No configuration for architecture $arch found;\n",
                "Please specify Arch=<NAME> or run ${top}configure.\n";
         } else {
            die "Please run ${top}configure prior to building anything;\n",
                "Try ${top}configure --help for more details.\n";
         }
      }
   } elsif ((my @builds=glob "${top}build.darwin.*")==1) {
      ($arch)= $builds[0] =~ m{build\.([^/]+)$};
   } else {
      die "Several configurations for MacOS platform found;\n",
          "Please specify the desired one using the option Arch=<NAME>.\n";
   }
   if (wantarray) {
      require Cwd;
      my @addlibs;
      if ($^O eq "darwin") {
	 open my $cf, "${top}build.$arch/conf.make";
	 while (<$cf>) {
	    if (/^FinkBase\s*=\s*(\S+)/) {
	       push @addlibs, "$1/lib/perl5";
	       last;
	    }
	 }
      }
      (Cwd::abs_path("${top}build.$arch"), $arch, @addlibs);
   } else {
      "${top}build.$arch"
   }
}

# Local Variables:
# mode: perl
# cperl-indent-level:3
# End:
