#!/usr/bin/perl

# Copyright (C) 1999-2003, Matevz Tadel. All rights reserved.
# This file is part of GLED, released under GNU General Public License version 2.
# For the licensing terms see $GLEDSYS/LICENSE or http://www.gnu.org/.

use Carp;
use ParseConfig;

########################################################################

sub exec_or_die {
  my $cmd = shift;
  my $ret = `$cmd`;
  croak "$cmd died" if $?;
  return $ret
}

sub system_or_die {
  my $cmd = shift;
  system "$cmd" and die "$cmd died";
}

########################################################################

$config  = {};

my $cfg_parser = new ParseConfig(-defcfg=>"configure.rc",
				 -useenv=>1,
				 -hash=>$config);
$cfg_parser->parse();

if($config->{HELP}) {
  print "./configure <options>\n";
  print "  options can be --<opt1>=<val1> or -<opt1> <val1>\n";
  print "  option names can be abbreviated\n";
  print "Options:\n";
  print '-' x 72 . "\n";
  print `cat configure.rc`;
  print '-' x 72 . "\n";

  exit 0;
}

$system = exec_or_die("uname -s"); chomp $system;
if($system eq 'Linux' or $system eq 'Darwin') {
  print "Configuring for '$system'.\n";
} else {
  print "Unsupported system '$system'. Reverting to 'Linux'.";
  $system = 'Linux';
}

########################################################################
# Basic build configure: create make_config.inc
########################################################################

my @ext_areas = split(':', $config->{EXTERNAL});

my $fltk_config = "fltk-config";
for $d (@ext_areas) {
  my $f = "$d/bin/fltk-config";
  $fltk_config = $f, last if -x $f;
}
my $fltk_version = `$fltk_config --version` or die "Can not find fltk-config.";

my @user_cxx_elms;
push @user_cxx_elms, "-g" if $config->{DEBUG};
push @user_cxx_elms, $config->{USER_CXX_FLAGS} if $config->{USER_CXX_FLAGS};
my $user_cxx = join(' ', @user_cxx_elms);

my @user_ld_elms;
# @user_ld_elms = map { "-L$_/lib" } @ext_areas;
push @user_ld_elms, $config->{USER_LD_FLAGS} if $config->{USER_LD_FLAGS};
my $user_ld  = join(' ', @user_ld_elms);

open MC, ">make_config.inc";
print MC <<"fnord";
ext           := $config->{EXTERNAL}
prefix        := $config->{PREFIX}

FLTK_CONFIG   := $fltk_config

USER_CXX_FLAGS = $user_cxx
USER_LD_FLAGS  = $user_ld

################################################################
### System '$system' specific settings
################################################################

fnord

if ($system eq 'Linux') {

  print MC <<"fnord";
LDEXT       := so
DASHDOT     := -
LDSHAREDOPT  = -shared
LD           = \${CXX}
fnord

}
elsif($system eq 'Darwin') {

print MC <<"fnord";
LDEXT       := dylib
DASHDOT     := .
LDSHAREDOPT  = -dynamiclib -undefined dynamic_lookup
LD           = \${CXX}
fnord

}
else {
  croak "Unknown system."
}

close MC;
