#!/usr/bin/perl
# $Header: /mnt/data/cvs/gled-1.2/gled-build/configure,v 1.3 2003/07/23 12:34:12 matevz Exp $

# 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 Data::Dumper;
use Carp;
use lib "$ENV{GLEDSYS}/perllib";
use ParseConfig;
use Gled_ConfCat_Parser;
use Gled_Installer;

$CFGFILE     = "build_config";

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

sub write_config {
  $Data::Dumper::Indent = 1;
  $Data::Dumper::Purity = 1;
  open BC, ">$CFGFILE" or die "can't open $CFGFILE";
  print BC Dumper($config, $resolver);
  close BC;
}

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

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";
}

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

sub deduce_libset_list {
  my @l;
  if($config->{LIBSETS} =~ m/^<file:([\w\.]+)>$/) {
    open F, $1 or croak "libset list file \"$1\" not found";
    while($_=<F>) {
      next if /^\#/ or /^\s*$/;
      chomp;
      push @l, $_;
    }
    close F;
  } elsif($config->{LIBSETS} eq '<auto>' or $config->{LIBSETS} eq '<auto-prompt>') {
    open F, 'find . -type d -name [A-Z]\* -maxdepth 1 -printf "%P\n" | grep -v CVS |';
    while($_=<F>) {
      chomp;
      push @l, $_;
    }
    close F;
    print "The following libsets will be configured for building:\n";
    print "  " . join(' ', @l) . "\n";
    if($config->{LIBSETS} eq '<auto-prompt>') {
      print "Is this OK? <y or enter for ok> ";
      my $answ = <STDIN>;
      unless($answ eq "\n" or $answ =~ m/^[yY]/) {
	print "aborting then ...\n";
	exit 0;
      }
    }
  } else {
    @l = split(/:/, $config->{LIBSETS});
    map { s!/$!! } @l; # filter off trailing '/'s
    my @sl = grep { m!/! } @l;
    if($#sl >= 0) {
      die "specified libset list contains '/' (" . join(', ', @sl) . ") ... not good";
    }
  }
  return @l;
}

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

sub find_base_dependency {
  my $ls = shift;
  my $sympath = undef;
  for $d (@base_dirs) {
    if(-d "$d/$ls") { return $d; }
    if(-l "$d/$ls" and not defined $sympath) { $sympath = $d; }
  }
  return $sympath;
}

sub collect_dependencies {
  my $libset = shift;
  my $deparr = shift;

  my $deps = exec_or_die("make -s -C $libset echo_requires_libsets");
  chomp $deps;
  my @deps = split /\s+/, $deps;
  for $d (@deps) {
    unless( grep(/^$d$/, @$deparr) ) {
      unless(-d $d or -l $d) {
	my $path = find_base_dependency($d);
	if(defined $path) {
	  print "Base $d found in path $path ... symlinking here\n";
	  symlink("$path/$d", "$d");
	} else {
	  die "Dependency $d of libset $libset not found ...";
	}
      }
      collect_dependencies($d, $dephash);
      push @$deparr, $d;
    }
  }
}

########################################################################
# MAIN
########################################################################

$config  = {};
$resolver= {};

$def_cfg = "$ENV{GLEDSYS}/configure.rc";

my $cfg_parser = new ParseConfig(-defcfg=>$def_cfg,
				 -useenv=>1,
				 -hash=>$config);
$cfg_parser->parse();

if($config->{HELP}) {
  print "usage: configure <options>\n";
  print "Options:\n";
  print `cat $def_cfg`;
  exit 0;
}

########################################################################
# Basic build configure
########################################################################

if($config->{RECONFIGURE} == 0) {

  # Basic configure: write config.h, makefile includes;
  #                  read build_libsets and produce resolver   

  print "BASE = $config->{GLEDBASE}, SYS = $ENV{GLEDSYS}, CFG = $CFGFILE\n";

  my @Rnrs = split(/:/, $config->{RENDERERS});
  my $renderers = join(' ', @Rnrs);

  # include/config.h
  # bluntly include stuff for gcc; will need compiler option ...
  open CH, ">include/config.h";

  print CH "#ifndef GLED_CONFIGURE_H\n";
  print CH "#define GLED_CONFIGURE_H\n\n";
  print CH "#include \"gcc-config.h\"\n\n";

  print CH "#define GLED_VERSION_STRING    \"$config->{BUILD_VERSION}\"\n";
  print CH "#define GLED_BUILD_DATE_STRING \"$config->{BUILD_DATE}\"\n";
  print CH "\n";

  $ch_line = "#define MAC_RNR_FRIENDS(_xx_) ";
  $ch_line .= join('; ', map(" friend class _xx_ ## _${_}_Rnr", @Rnrs));
  print CH $ch_line."\n\n";

  print CH "#endif\n";
  close CH;

  # make/make_config.inc
  my @ext_areas = split(':', $config->{EXTERNAL});
  my @user_cpp_elms;
  push @user_cpp_elms, "-DDEBUG" if($config->{DEBUG});
  push @user_cpp_elms, map { "-I$_/include" } @ext_areas;
  push @user_cpp_elms, $config->{USER_CPP_FLAGS} if $config->{USER_CPP_FLAGS};
  my $user_cpp = join(' ', @user_cpp_elms);
  my @user_cxx_elms;
  push @user_cxx_elms, ($config->{DEBUG} ? "-g" : "-O");
  push @user_cxx_elms, $config->{USER_CXX_FLAGS} if $config->{USER_CXX_FLAGS};
  my $user_cxx = join(' ', @user_cxx_elms);
  my @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/make_config.inc";
  print MC <<"fnord";
GLUE_DIR := $config->{GLUE_DIR}
DICT_DIR := $config->{DICT_DIR}
VIEW_DIR := $config->{VIEW_DIR}

USER_CPP_FLAGS = $user_cpp
USER_CXX_FLAGS = $user_cxx
USER_LD_FLAGS  = $user_ld
fnord
  close MC;

  # make/make_rnr.inc
  open MC, ">make/make_rnr.inc";
  print MC "RENDERERS\t:= $renderers\n\n";
  for $rnr (@Rnrs) {
    print MC "ABOVE_RNR_${rnr}_LIBS\t= \$(addsuffix _Rnr_${rnr}, \$(addprefix -l, \${REQUIRES_LIB_SETS}))\n";
    print MC "${rnr}_RNR_SRCS\t:= \$(wildcard Rnr/${rnr}/*.cxx) " .
      "$config->{GLUE_DIR}/\${LIB_SET_NAME}_Rnr_${rnr}_LibSet.cxx\n";
    print MC "${rnr}_RNR_HDRS\t:= \$(wildcard Rnr/${rnr}/*.h) " .
      "$config->{GLUE_DIR}/\${LIB_SET_NAME}_Rnr_${rnr}_LibSet.h\n";
    print MC "${rnr}_RNR_OBJS\t:= \$(${rnr}_RNR_SRCS:.cxx=.o)\n";
    print MC "${rnr}_RNR_LIB_NAME\t:= lib/lib\${LIB_SET_NAME}_Rnr_$rnr.so\n";

    print MC "\${${rnr}_RNR_LIB_NAME}:\t \${${rnr}_RNR_OBJS}\n";
    print MC "\t\${LD} -o \${${rnr}_RNR_LIB_NAME} -shared \${${rnr}_RNR_OBJS} -L\${GLEDSYS}/lib \\\n" .
      "\t\t\${ABOVE_BASE_LIBS} \${ABOVE_VIEW_LIBS} \${ABOVE_RNR_${rnr}_LIBS} \${LD_SURPLUS}\n";
    print MC "RNR_SRCS += \${${rnr}_RNR_SRCS}\n";
    print MC "RNR_HDRS += \${${rnr}_RNR_HDRS}\n";
    print MC "RNR_OBJS += \${${rnr}_RNR_OBJS}\n";
    print MC "\n";
  }
  print MC "RNR_LIBS := " . join(' ', map { "\${${_}_RNR_LIB_NAME}" } @Rnrs) . "\n";
  close MC;

} else {

  # Reconfigure: read build_libsets, build resolver

  Gled_ConfCat_Parser::import_build_config();

  print "BASE = $config->{GLEDBASE}, SYS = $ENV{GLEDSYS}, CFG = $CFGFILE\n";
}

$resolver = {};
$resolver->{LibSetList} = [];

@libsets = ();
@base_libsets = ();
%deps = ();

@base_dirs = split(/\s*:\s*/, $config->{GLEDBASE});

########################################################################
# configure of libset dependencies and building of resolver
########################################################################

# Study libsets, assert directories exist, dependencies fulfilled
for $lib_set (deduce_libset_list()) {
  die "$lib_set not existing ..." unless -d $lib_set;
  push @libsets, $lib_set;

  my @lsdeps = ();
  collect_dependencies($lib_set, \@lsdeps);
  $deps{$lib_set} = \@lsdeps;
  if($#lsdeps==-1) {
    push @ok_libsets, $lib_set;
  }
}

# grep for base libsets (those that need to be installed, but not bulit)
for $ls (@libsets) {
  for $lsd (@{$deps{$ls}}) {
    unless( grep(/^$lsd$/, @libsets) ) {
      push(@base_libsets, $lsd) unless grep(/^$lsd$/, @base_libsets);
    }
  }
}

# Resolve dependencies ... must build libsets in proper order
my $npass = 1;
eliminator: {
  my $nok1 = $#ok_libsets;
  print "Pass $npass, nok=$nok1\n" if $config->{CONFDEBUG};
ls_loop:
  for $ls (@libsets) {
    next ls_loop if grep(/^$ls$/, @ok_libsets);
    for $lsd (@{$deps{$ls}}) {
      print "Checking dep $lsd for libsets $ls ... " if $config->{CONFDEBUG};
      if( grep(/^$lsd$/, @libsets) ) {
	unless( grep(/^$lsd$/, @ok_libsets) ) {
	  print "failed\n" if $config->{CONFDEBUG};
	  next ls_loop;
	}
	print "ok\n" if $config->{CONFDEBUG};
      } elsif( grep(/^$lsd$/, @base_libsets) ) {
	print "ok in base\n" if $config->{CONFDEBUG};
      } else {
	die "dependency $lsd not found";
      }
    }
    push @ok_libsets, $ls;
    print "Resolved $ls\n" if $config->{CONFDEBUG};
  }
  last eliminator if $#ok_libsets == $#libsets;
  die "Failed resolving dependecies, ok=(".join(',',@ok_libsets).")"
    if($nok1 == $#ok_libsets);
  print "Reentering ... final nok=$#ok_libsets\n" if $config->{CONFDEBUG};
  redo eliminator;
}

# Build resolver
%libid_check = ();

for $f (@ok_libsets, @base_libsets) {
  my $lid = exec_or_die("make -s -C $f echo_libset_id");
  chomp $lid;
  die "LibId conflict for $f" if exists $libid_check{$lid};
  $libid_check{$lid} = 1;
  $resolver->{LibName2LibSpecs}{$f}{LibID} = $lid;
}

$resolver->{BaseLibSetList} = \@base_libsets;
$resolver->{LibSetList}     = \@ok_libsets;

for $f (@ok_libsets) {
  $resolver->{LibName2LibSpecs}{$f}{CPP_FLAGS} =
    join(' ', (map {"-I$ENV{GLEDSYS}/$_" } @{$deps{$f}}));
}

# Write first version of build_config, uncomplete resolver
write_config();

# Make build_install & install from BaseLibSets elements
for $f (@{$resolver->{BaseLibSetList}}) {
  system_or_die("make -C $f build_install install");
}

# Make base_install from local LibSets
for $f (@{$resolver->{LibSetList}}) {
  system_or_die("make -C $f build_install");
}

# Generate catalogs, dictionaries, views and Rnr bindings
for $f (@{$resolver->{LibSetList}}) {
  system_or_die("make -C $f pre_depend");
}

########################################################################
# Merge libset catalogs into resolver
########################################################################

for $f ((map {"$config->{GLEDBASE}/$_"} @{$resolver->{BaseLibSetList}}),
	@{$resolver->{LibSetList}})
  {
    Gled_ConfCat_Parser::parse_catalog($f);
    $resolver->{LibID2LibSetName}{$CATALOG->{LibID}} = $CATALOG->{LibSetName};
    for $c (@{$CATALOG->{ClassList}}) {
      $resolver->{GlassName2GlassSpecs}{$c} =
	{
	 'LibSetName' => $f, 'ClassName' => $c,
	 'LibID' => $CATALOG->{LibID}, 'ClassID' => $CATALOG->{Classes}{$c}{ClassID},
	 'FileStem' => "$ENV{GLEDSYS}/$f/$CATALOG->{Classes}{$c}{Stem}"
	};
    }
  }

# Write final version of build_config, full glass catalog included
write_config();

# Now run make depend
for $f (@{$resolver->{LibSetList}}) {
  system_or_die("make -C $f depend");
}

########################################################################
# Create Makefile
########################################################################

{
  open M, ">Makefile";
  print M "# This Makefile has been autogenerated by configure.\n";
  print M "# Use './configure --reconfigure' to change affected libsets\n";
  print M "\n";

  print M "SUBDIRS := ", join(' ', @{$resolver->{LibSetList}}), "\n";
  print M "BUILD_FILES := $CFGFILE Makefile \\\n";
  print M "  make/make_config.inc make/make_rnr.inc include/config.h\n";
  print M "\n";

  print M "all:\n\n";

  print M "\%:\n";
  for $f (@{$resolver->{LibSetList}}) { print M "\t\${MAKE} -C $f \$\@\n"; }
  print M "\n";

  print M <<"FNORD";
distclean::

distclean::
	rm -f \${BUILD_FILES}
FNORD

  close M;
}

# print Dumper(\@libsets);
# print Dumper(\%deps);
# print Dumper(\@ok_libsets);
# print Dumper(\@base_libsets);
# print Dumper($resolver);
