#!/usr/bin/perl
# Copyright (C) 1996,1997,1998,1999 by Salvador E. Tropea (SET),
# see copyrigh file for details
#

require "miscperl.pl";
require "conflib.pl";

$conf{'infview'}='yes';

GetCache();
GetVersion('');

$TVVersionNeeded='1.0.8';
$ZLibVersionNeeded='1.1.2';
$DJGPPVersionNeeded='2.0.2';
# Allegro 3.1==3.0.1 3.11==3.0.11 3.12==3.0.12
$AllegroVersionNeeded='3.0.1';
# 3.9.x are WIPs
$AllegroNotNeeded='3.9.0';
unlink $ErrorLog;

SeeCommandLine();

print "Configuring SETEdit v$Version\n\n";
# Determine the OS
$OS=DetectOS();
$supportDir='makes/'.$supportDir;
LookForPrefix();
# Determine C flags
$CFLAGS=FindCFLAGS();
# Determine C++ flags
$CXXFLAGS=FindCXXFLAGS();
# Test for a working gcc
$GCC=CheckGCC();
# Check if gcc can compile C++
$GXX=CheckGXX();

# Is the right djgpp?
if ($OS eq 'dos')
  {
   LookForDJGPP($DJGPPVersionNeeded);
   LookForAllegro($AllegroVersionNeeded,$AllegroNotNeeded);
  }

# Where is the TV library?
# $TVInclude and $TVLib
LookForTV();
# Is the right version?
TestTVVersion($TVVersionNeeded);

# Is PCRE available?
LookForPCRE();
# Is ZLib available?
LookForZLib($ZLibVersionNeeded);

print "\n";
GenerateMakefile();
#
# Create a list of RHIDE variables to configure the projects
#
$TVLib='../'.$TVLib if (substr($TVLib,0,2) eq '..');
$TVInclude='../'.$TVInclude if (substr($TVInclude,0,2) eq '..');
$shipped=(@conf{'zlibShipped'} eq 'yes') || (@conf{'PCREShipped'} eq 'yes');
if ($OS eq 'dos')
  {
   $MakeDefsRHIDE[0]='RHIDE_STDINC=$(DJDIR)/include $(DJDIR)/lang/cxx $(DJDIR)/lib/gcc-lib';
   $MakeDefsRHIDE[1]='RHIDE_OS_LIBS=intl';
   $MakeDefsRHIDE[1].=' amp alleg' if (@conf{'HAVE_ALLEGRO'} eq 'yes');
   $MakeDefsRHIDE[2]="RHIDE_OS_LIBS_PATH=$TVLib";
   $MakeDefsRHIDE[2].=' djgpp' if $shipped;
  }
else
  {
   $MakeDefsRHIDE[0]='RHIDE_STDINC=/usr/include /usr/local/include /usr/include/g++ /usr/local/include/g++ /usr/lib/gcc-lib /usr/local/lib/gcc-lib';
   $MakeDefsRHIDE[1]='RHIDE_OS_LIBS=ncurses gpm m';
   $MakeDefsRHIDE[2]="RHIDE_OS_LIBS_PATH=$TVLib";
   $MakeDefsRHIDE[2].=' linux' if $shipped;
  }
$MakeDefsRHIDE[3]="TVISION_INC=$TVInclude";
$MakeDefsRHIDE[4]='SUPPORT_INC=';
$MakeDefsRHIDE[4].='../support' if $shipped;
if (@conf{'static'} eq 'yes')
  {
   $MakeDefsRHIDE[5]='RHIDE_COMPILE_LINK=$(RHIDE_LD) $(RHIDE_LIBDIRS) $(LDFLAGS) -static $(RHIDE_LDFLAGS) $(C_EXTRA_FLAGS) -o $(OUTFILE)  $(OBJFILES) $(LIBRARIES) $(RHIDE_LIBS)';
  }
else
  {
   $MakeDefsRHIDE[5]='RHIDE_COMPILE_LINK=$(RHIDE_LD) $(RHIDE_LIBDIRS) $(LDFLAGS) $(RHIDE_LDFLAGS) $(C_EXTRA_FLAGS) -o $(OUTFILE)  $(OBJFILES) $(LIBRARIES) $(RHIDE_LIBS)';
  }
CreateRHIDEenvs('makes/rhide.env','mp3/libamp/rhide.env');
#
# Now pass the options in rhide.env to the makefiles
#
print "Configuring .mak files\n";
chdir('makes');
#system("perl patchenv.pl");
`perl patchenv.pl`;
chdir('..');
CreateConfigH();

print "\nSuccesful configuration!\n\n";

GiveAdvice();
CreateCache();
unlink $ErrorLog;


sub SeeCommandLine
{
 my $i;

 foreach $i (@ARGV)
   {
    if ($i eq '--help')
      {
       ShowHelp();
       die "\n";
      }
    elsif ($i=~'--prefix=(.*)')
      {
       $conf{'prefix'}=$1;
      }
    elsif ($i eq '--static')
      {
       $conf{'static'}='yes';
      }
    elsif ($i eq '--fhs')
      {
       $conf{'fhs'}='yes';
      }
    elsif ($i eq '--libset')
      {
       $conf{'libset'}='yes';
      }
    elsif ($i eq '--no-libset')
      {
       $conf{'libset'}='no';
      }
    elsif ($i eq '--infview')
      {
       $conf{'infview'}='yes';
      }
    elsif ($i eq '--no-infview')
      {
       $conf{'infview'}='no';
      }
    else
      {
       ShowHelp();
       die "Unknown option: $i\n";
      }
   }
}

sub ShowHelp
{
 print "Available options:\n\n";
 print "--help         : displays this text.\n";
 print "--prefix=path  : defines the base directory for installation.\n";
 print "--static       : force to create an statically linked executable.\n";
 print "--fhs          : force the FHS layout under UNIX.\n";
 print "--libset       : create libset, needed to compile RHIDE.\n";
 print "--no-libset    : don't create libset [default].\n";
 print "--infview      : also compile InfView [default].\n";
 print "--no-infview   : don't compile InfView, just the editor.\n";
}

sub GiveAdvice
{
 if (@conf{'HAVE_PCRE_LIB'} eq 'no')
   {
    print "\n";
    print "* The Perl Compatible Regular Expressions support was disabled install PCRE\n";
    print "  library v2.0 or newer and reconfigure to get support.\n";
   }
 if (($OS eq 'dos') && (@conf{'HAVE_ALLEGRO'} eq 'no'))
   {
    print "* The MPEG-3 files support was disabled, install Allegro library v$AllegroVersionNeeded\n";
    print "  or newer (not a WIP!) and reconfigure to get support.\n";
   }
}

sub LookForTV
{
 my @dirsI,@dirsL,$parent;

 print 'Looking for installed Turbo Vision: ';
 if (@conf{'TV_INCLUDE'})
   {
    $TVInclude=@conf{'TV_INCLUDE'};
    $TVLib=@conf{'TV_LIB'};
    print "\n\tInclude dir: $TVInclude (cached)\n";
    print "\tLibrary dir: $TVLib (cached)\n";
    return;
   }
 #$parent=ParentDir();
 $parent='..';
 if ($OS eq 'dos')
   {
    @dirsI=("$parent/tvision/include",$ENV{'DJDIR'}.'/include/tvision');
    @dirsL=("$parent/tvision/djgpp",$ENV{'DJDIR'}.'/lib');
   }
 else
   {
    @dirsI=("$parent/tvision/include",'/usr/include/rhtvision');
    @dirsL=("$parent/tvision/linuxso","$parent/tvision/linux",'/usr/lib');
   }
 $TVInclude=LookForFile('tv.h',@dirsI);
 if (!length($TVInclude))
   {
    print "\n\nError: Can't find an installed version, please install Turbo Vision first.\n";
    print "The headers should be installed in one of the following directories:\n@dirsI\n";
    CreateCache();
    die "Missing library\n";
   }
 print "\n\tInclude dir: $TVInclude\n";
 $TVLib=LookForFile('librhtv.[as]*',@dirsL);
 if (!length($TVLib))
   {
    print "\nError: Can't find a compiled version, please compile Turbo Vision first.\n";
    print "The library should be installed in one of the following directories:\n@dirsL\n";
    CreateCache();
    die "Missing library\n";
   }
 print "\tLibrary dir: $TVLib\n";
 $conf{'TV_INCLUDE'}=$TVInclude;
 $conf{'TV_LIB'}=$TVLib;
}

sub LookForPCRE
{
 my $test205,$test206,$t2,$test,$dir;

 print 'Looking for PCRE library: ';
 $test=@conf{'HAVE_PCRE_LIB'};
 if ($test)
   {
    print "$test (cached)\n";
    return;
   }
 $test205='
#include <stdio.h>
#include <stdlib.h>
#include <pcre.h>
int main(void)
{
 pcre *compiled;
 int flags=PCRE_MULTILINE | PCRE_CASELESS;
 const char *error;
 int   errorOffset,hits,max,*matchs;
 compiled=pcre_compile("test",flags,&error,&errorOffset,0);
 if (!compiled) return 1;
 max=(pcre_info(compiled,0,0)+1)*3;
 matchs=(int *)malloc(max*sizeof(int));
 hits=pcre_exec(compiled,0,"This is just a test 123",23,';
 $t2='0,matchs,max);
 if (hits!=1) return 1;
 printf("OK\n");
 return 0;
}';
 $test206=$test205.'0,'.$t2;
 $test205.=$t2;

 # See if 2.0.6+ is installed
 $test=RunGCCTest($GCC,'c',$test206,"-lpcre");
 if ($test eq "OK\n")
   {
    print "v2.0.6 or better OK\n";
    $conf{'HAVE_PCRE_LIB'}='yes';
    $conf{'HAVE_PCRE206'}='yes';
    $conf{'PCREShipped'}='no';
    return;
   }
 print 'no 2.0.6+, ';
 # See if 2.0+ is installed
 $test=RunGCCTest($GCC,'c',$test205,"-lpcre");
 if ($test eq "OK\n")
   {
    print "v2.0 or better OK\n";
    $conf{'HAVE_PCRE_LIB'}='yes';
    $conf{'HAVE_PCRE206'}='no';
    $conf{'PCREShipped'}='no';
    return;
   }
 print 'no 2.0+, ';
 # See if the one shipped works here
 $test=RunGCCTest($GCC,'c',$test206,"-L$supportDir -lpcre -Isupport");
 if ($test ne "OK\n")
   {
    print "no shipped, disabling PCRE\n";
    $conf{'HAVE_PCRE_LIB'}='no';
    $conf{'HAVE_PCRE206'}='no';
    $conf{'PCREShipped'}='no';
    return;
   }

 $conf{'HAVE_PCRE_LIB'}='yes';
 $conf{'HAVE_PCRE206'}='yes';
 $conf{'PCREShipped'}='yes';
 print "using shipped one.\n";
}

sub TestTVVersion
{
 my $vNeed=$_[0];
 my $test;

 print 'Checking TV version: ';
 $test=@conf{'tv'};
 if ($test)
   {
    print "$test (cached) OK\n";
    return;
   }
 $test='
#include <stdio.h>
#include <tv.h>
int main(void)
{
 printf("%d.%d.%d",TV_MAJOR_VERSION,TV_MIDDLE_VERSION,TV_MINOR_VERSION);
 return 0;
}';
 $test=RunGCCTest($GXX,'cc',$test,"$stdcxx -I$TVInclude");
 if (!CompareVersion($test,$vNeed))
   {
    print "\nWrong TV version, please use $vNeed or newer\n";
    print "Look in $ErrorLog for potential compile errors of the test\n";
    CreateCache();
    die "Wrong version\n";
   }
 print "$test OK\n";
 $conf{'tv'}=$test;
}


sub LookForAllegro
{
 my $vNeed=$_[0],$vMaxV=$_[1];
 my $test;

 print 'Looking for Allegro library: ';

 $test=@conf{'HAVE_ALLEGRO'};
 if ($test)
   {
    print "$test (cached)\n";
    return;
   }
 $test='
#include <stdio.h>
#include <allegro.h>
int main(void)
{
 allegro_init();
 // Defined by 3.9.x
 #ifdef ALLEGRO_WIP_VERSION
 print ("%d.%d.%d",ALLEGRO_VERSION,ALLEGRO_SUB_VERSION,ALLEGRO_WIP_VERSION);
 #else
 printf("%d.0.%d",ALLEGRO_VERSION,ALLEGRO_SUB_VERSION);
 #endif
 return 0;
}';
 $MP3Support=0;
 $test=RunGCCTest($GCC,'c',$test,"-lalleg");
 if (!length($test))
   {
    print "not installed, disabling MP3 support.\n";
    $conf{'HAVE_ALLEGRO'}='no';
    return;
   }
 if (!CompareVersion($test,$vNeed))
   {
    print "$test -> No, disabling MP3 support.\n";
    print "\nWrong Allegro version, please use $vNeed or newer, but not greater or equal\n";
    print "to $vMaxV.\n\n";
    $conf{'HAVE_ALLEGRO'}='no';
    return;
   }
 if (CompareVersion($test,$vMaxV))
   {
    print "$test -> No, disabling MP3 support.\n";
    print "\nSorry, I need a non-WIP release\n\n";
    $conf{'HAVE_ALLEGRO'}='no';
    return;
   }
 $MP3Support=1;
 $conf{'HAVE_ALLEGRO'}='yes';
 print "$test OK\n";
}


sub LookForZLib
{
 my $vNeed=$_[0];
 my $test,$ver;

 print 'Looking for zlib: ';
 $test=@conf{'zlib'};
 if ($test)
   {
    print "$test (cached) OK\n";
    return;
   }
 $test='
#include <stdio.h>
#include <zlib.h>
int main(void)
{
 gzFile f;
 f=gzopen("","rb");
 printf("%s",ZLIB_VERSION);
 return 0;
}';
 $ver=RunGCCTest($GCC,'c',$test,'-lz');
 if (length($ver))
   {
    if (CompareVersion($ver,$vNeed))
      {
       print "$ver OK\n";
       $conf{'zlibShipped'}='no';
       $conf{'zlib'}=$ver;
       return;
      }
    print "no $vNeed+, ";
   }
 else
   {
    print 'not installed, ';
   }
 $test=RunGCCTest($GCC,'c',$test,"-lz -Isupport -L$supportDir");
 if (!CompareVersion($test,$vNeed))
   {
    print "no shipped\n";
    print "\n\nError: Can't find an installed version, please install zlib 1.1.2 or better first.\n";
    CreateCache();
    die "Missing library\n";
   }
 print "shipped $test OK\n";
 $conf{'zlibShipped'}='yes';
 $conf{'zlib'}=$test;
}

sub CreateConfigH
{
 my $text="/* Generated automatically by the configure script */";

 print "Generating configuration header\n";

 $text.=ConfigIncDefYes('HAVE_ALLEGRO','Allegro library is available');
 $text.=ConfigIncDefYes('HAVE_PCRE_LIB','Perl Compatible Regular Expressions support');
 $text.=ConfigIncDefYes('HAVE_PCRE206','PCRE version 2.0.6 or newer');
 $text.="\n";

 replace('include/configed.h',$text);
}

sub GenerateMakefile
{
 my $text="# Generated automatically by the configure script";
 my $libamp,$libset,$infview;

 print "Generating Makefile\n";

 $text.="\n\nPREFIX=$conf{'prefix'}";
 $text.="\nlibdir=\$(PREFIX)/lib";
 $text.="\nCFLAGS=$conf{'CFLAGS'}";
 $text.="\nCXXFLAGS=$conf{'CXXFLAGS'}";
 $text.="\nSET_USE_FHS=$conf{'fhs'}" unless ($OS eq 'dos');
 $text.="\nexport";

 #### Targets ####
 $libset=@conf{'libset'} eq 'yes';
 $libamp=@conf{'HAVE_ALLEGRO'} eq 'yes';
 $infview=$conf{'infview'} eq 'yes';
 $plasmas=$OS eq 'dos';
 $text.="\n\n.PHONY:" if ($infview || $plasmas);
 $text.=" infview" if ($infview);
 $text.=" plasmas" if ($plasmas);
 # all targets
 $text.="\n\nall: editor";
 $text.=" libset" if ($libset);
 $text.=" infview" if ($infview);
 $text.=" plasmas" if ($plasmas);
 $text.="\n";
 # libamp
 if ($libamp)
   {
    $text.="\n\nlibamp:\n";
    $text.="\t\$(MAKE) -C mp3/libamp -f libamp.mak";
   }
 # editor
 $text.="\n\neditor:";
 $text.=" libamp" if ($libamp);
 $text.="\n\t\$(MAKE) -C makes";
 # libset
 if ($libset)
   {
    $text.="\n\nlibset:\n";
    $text.="\tcd makes; \$(MAKE) -f libset.mak; cd ..";
   }
 # infview
 if ($infview)
   {
    $text.="\n\ninfview:\n";
    $text.="\t\$(MAKE) -C makes infview";
   }
 # plasmas
 if ($plasmas)
   {
    $text.="\n\nplasmas:\n";
    $text.="\tcd scrnsave; \$(MAKE); cd ..";
   }

 #### Installations ####
 # editor
 $text.="\n\ninstall-editor: editor\n";
 $text.="\t\$(MAKE) -C makes install";
 # libset
 if ($libset)
   {
    $text.="\n\ninstall-libset: libset\n";
    $text.="\tinstall -d -m 0755 \$(libdir)\n";
    $text.="\tinstall -m 0644 makes/libset.a \$(libdir)";
   }
 # infview
 if ($infview)
   {
    $text.="\n\ninstall-infview: infview\n";
    $text.="\t\$(MAKE) -C makes install-infview";
   }
 # all targets
 $text.="\n\ninstall: install-editor";
 $text.=" install-libset" if ($libset);
 $text.=" install-infview" if ($infview);
 $text.="\n";

 $text.="\nclean:\n";
 $text.="\tcd makes; \$(MAKE) clean-o; \$(MAKE) clean-docs; cd ..\n";
 $text.="\trm -f configure.cache\n";
 $text.="\trm -f Makefile\n";
 $text.="\trm -f errormsg.txt\n";
 $text.="\trm -f doc/sdh.exe\n";
 $text.="\trm -f include/configed.h\n";
 $text.="\trm -rf makes/linux/result makes/linux/resultInf makes/linux/setedit-* makes/linux/infview-*\n" if ($OS eq 'linux');
 $text.="\trm -rf makes/djgpp/distinf makes/djgpp/distrib makes/djgpp/result makes/djgpp/resulinf\n" if ($OS eq 'dos');
 $text.="\trm -f makes/*.a makes/*.exe makes/*.gdt\n";
 $text.="\trm -f mp3/libamp/*.a mp3/libamp/obj/*.o\n";
 $text.="\tcd scrnsave; \$(MAKE) clean-o; cd ..\n" if ($plasmas);

 replace('Makefile',$text);
}
