#!/bin/sh -- # -*- perl -*-
eval 'exec perl -S $0 "$@"'
    if 0;
########################## -*- Mode: Perl -*- ##########################
##
## File             : Construct
##
## Description      : 
##
## Author           : Norbert Goevert
## Created On       : Tue Sep  3 11:23:48 1996
##
## Last Modified By : Norbert Goevert
## Last Modified On : Wed Feb 12 17:13:02 1997
##
## $State: Exp $
##
## $Id: Construct,v 5.1.1.2 1997/02/17 12:54:14 goevert Exp goevert $
##
## $Log: Construct,v $
## Revision 5.1.1.2  1997/02/17 12:54:14  goevert
## patch10: Perl 3.00307 or higher required
##
## Revision 5.1.1.1  1996/12/23 12:44:13  goevert
## patch6: UNIX domain sockets, organization of log files
##
## Revision 5.1  1996/11/05 16:52:34  goevert
## *** empty log message ***
##
## Revision 5.0.1.1  1996/11/04 13:05:07  goevert
## patch21: cons instead of MakeMaker
##
########################################################################


# some globals
require Config;
$perlversion = 5.003;
$waisversion = 2.118;
$configfile  = 'config.sh';
%::Config = ();


# configuration
if (! -e $configfile || $ARG{configure} || $ARG{show}) {
    &configure;
    exit if !$ARG{show};
}
else {
    &readconfig;
    $::CONFIG{REVISION} = &get_revision;
}


## #####################################################################
## Cons rules
## #####################################################################

# additional libs needed?
my $libs = '';
$libs = '-lnsl -lsocket' if `uname -r` =~ /^5/;

$CONS = new cons (CPPPATH => "$Config::Config{installarchlib}/CORE",
                  CC      => $Config::Config{cc},
                  ENV     => { PATH => $ENV{PATH} },
                  LIBS    => $libs,
                  CFLAGS  => $::CONFIG{CFLAGS}
                 );

Export qw(CONS);

Link 'build/SFproxy' => 'SFproxy';
Link 'build/doc'     => 'doc';
Link 'build/lib'     => 'lib';
Link 'build/source'  => 'source';

Build qw(build/SFproxy/Conscript
         build/doc/Conscript
         build/lib/Conscript
         build/source/Conscript
         tests/Conscript
        );

if ($::CONFIG{VERSION} eq 'gold') {
      
    Link 'build/C'     => 'C';
    Link 'build/forms' => 'forms';

    Build qw(build/C/Conscript
             build/forms/Conscript
            );
}

Install $CONS $::CONFIG{APPDIR}, 'lattice';

if (($devel = $ARG{devel}) && -e 'devel/Conscript') {
    $host = '';
    $host = $ARG{host} if $ARG{host};

    Export qw(CONS devel host);
    Build 'devel/Conscript';
}


## #####################################################################
## subs
## #####################################################################

sub configure
{
    &readconfig if -e $configfile;

    # That's this program:
    $::CONFIG{PROGRAM} = 'SFgate';

    # SFgate or SFgate-gold?
    if (-d 'C') {
        $::CONFIG{VERSION} = 'gold';
    }
        
    # SFgate version
    $::CONFIG{REVISION} = &get_revision;

    my $version = "-$::CONFIG{VERSION}";
    $version =~ s/^-$//;
    print "\n", ' ' x int((80 - length("*** This is SFgate$version $::CONFIG{REVISION} ***"))/2);
    print "*** This is SFgate$version $::CONFIG{REVISION} ***\n";
    
    # where is this perl?
    $::CONFIG{PERLBIN} = $^X;
    $::CONFIG{PERLBIN} =~ s!^.*/!!;
    $::CONFIG{PERLBIN} = $Config::Config{binexp} . '/' . $::CONFIG{PERLBIN};
    $::CONFIG{STARTPERL} = $Config::Config{startperl};

    # which host?
    my $host;
    eval {
        use Sys::Hostname;
        $host = hostname;
    };
    $::CONFIG{HOSTNAME} = $host . $Config::Config{mydomain};
    
    # test Perl version
    if ($] < $perlversion) {
        print <<"EOF";

Your Perl version is less than $perlversion. Please install a Perl with version $perlversion
or higher. Get it from CPAN: http://www.perl.com/

EOF
;
        die;
    }
    else {
        print "\nYour perl has version $perlversion or higher. Ok!\n";
    }
    
    # test availability and version of the Wais.pm library
    eval { require Wais; };
    if ($@ || $Wais::VERSION < $waisversion) {
        print "$@\n" if $@; 
        print <<"EOF";

I could not find a Wais module revision $waisversion or higher in the include path.
You must install that first. Get if from CPAN:
http://www.perl.com/CPAN/authors/id/ULPFR/

EOF
;
        die;
    }
    else {
        print "\nWais.pm with verion $waisversion or higher found. Ok!\n";
    }
        
    ##
    ## questions section
    ##

    # installation directory for libraries
    $::CONFIG{SITELIBEXP} = $Config::Config{sitelibexp};
    if (exists $::CONFIG{LIBDIR} && $::CONFIG{LIBDIR} eq '') {
        $::CONFIG{LIBDIR} = $::CONFIG{SITELIBEXP};
    }
    &ask_for('LIBDIR',
             qq[\nWhere should the Perl libraries go],
             $::CONFIG{SITELIBEXP});
    if ($::CONFIG{LIBDIR} eq $::CONFIG{SITELIBEXP}) {
        $::CONFIG{LIBDIR} = '';
    }
    
    # installation directory for utilities
    $::CONFIG{SCRIPTDIREXP} = $Config::Config{scriptdirexp};
    if (exists $::CONFIG{SCRIPTDIR} && $::CONFIG{SCRIPTDIR} eq '') {
        $::CONFIG{SCRIPTDIR} = $::CONFIG{SCRIPTDIREXP};
    }
    &ask_for('SCRIPTDIR',
             qq[\nWhere should the Perl utilities go],
             $::CONFIG{SCRIPTDIREXP});
    if ($::CONFIG{SCRIPTDIR} eq $::CONFIG{SCRIPTDIREXP}) {
        $::CONFIG{SCRIPTDIR} = '';
    }
        
    # the default directory to search WAIS databases
    print <<"EOF";

To simplify the specification of (local) databases in your
SFgate application forms enter the default directory where
SFgate can find the local wais databases. If you don\'t want
to use a default directory answer with \'none\'.
EOF
    ;

    &ask_for('DBDIR',
             q[What is the default path to the local wais databases],
             q[/home/robots/wais/wais-sources]);

    # http proxy
    print <<"EOF";

The next question is about your desired http proxy.
SFgate has a buildin http client, which can use a proxy.
If you don\'t have a proxy server or you don\'t want to
use it, answer 'none'.
EOF
;
    
    &ask_for('HTTPPROXY',
             q[What is your http proxy],
             q[none]);
    
    if ($::CONFIG{HTTPPROXY}) {
        &ask_for('HTTPPROXYPORT',
                 qq[\nWhat is the port of your http proxy],
                 q[80]);
    }
    
    # root directory for www pages
    &ask_for('WWWROOT',
             qq[\nWhere do your html pages reside],
             q[/home/robots/www/public-html]);
    
    # directory for documentation
    &ask_for('DOCDIR',
             qq[\nWhere - relative to $::CONFIG{WWWROOT}/ -\nshould the documentation go],
             q[SFgate]);
    $::CONFIG{REAL_DOCDIR} = $::CONFIG{WWWROOT} . '/' . $::CONFIG{DOCDIR};
    
    # virtual document directory
    print <<"EOF";

Virtual name means the name you want to use in URLs,
for example in \'http://somehost.some.domain/SFgate/demo.html\'
the virtual name of the document directory is '/SFgate'
EOF
    ;
    &ask_for('VIRTUAL_DOCDIR',
             qq[What is the virtual name of $::CONFIG{REAL_DOCDIR}],
             '/' . $::CONFIG{DOCDIR});
    
    # installation directory for the SFgate binary
    &ask_for('CGIBIN',
             qq[\nWhere is your real CGI dir for SFgate],
             qq[$::CONFIG{REAL_DOCDIR}/cgi-bin]);
    
    # virtual directory for the SFgate binary
    &ask_for('HTBIN',
             qq[\nWhat is the virtual name of $::CONFIG{CGIBIN}],
             qq[$::CONFIG{VIRTUAL_DOCDIR}/cgi-bin]);
    
    # directory for SFgate's application files
    &ask_for('APPDIR',
             qq[\nIn which directory should the application files go],
             q[/home/robots/www/etc/SFgate]);
    
    # use SFgate server
    if ($::CONFIG{VERSION} eq 'gold') {
        &ask_for('USESERVER',
                 qq[\nDo you want to use the new client/server architecture for SFgate],
                 q[y]);
    }
    
    if ($::CONFIG{USESERVER} =~ /^y/i) {

        $::CONFIG{USESERVER} = 'y';
        $::CONFIG{STARTSERVER} = $::CONFIG{CGIBIN} . '/SFgate-server';
        if (-d '/home/crew/goevert') {
            $::CONFIG{SFGATEID} =~ s/^\.//;
            &ask_for('SFGATEID',
                     qq[\nWhich ID should this installation be assigned],
                     q[1]);
            $::CONFIG{SFGATEID} = ".$::CONFIG{SFGATEID}" if $::CONFIG{SFGATEID} =~ /^\d+$/;
            my $libdirconfig = $::CONFIG{LIBDIR};
            $libdirconfig = $::CONFIG{SITELIBEXP} unless $libdirconfig;
            my $id = $::CONFIG{SFGATEID};
            $id =~ s/^\.//;
            $libdirconfig .= "/SFgate/ID$id";
            $::CONFIG{LIBDIRCONFIG} = $libdirconfig;
        }
        else {
            $::CONFIG{LIBDIRCONFIG} = $::CONFIG{LIBDIR};
            $::CONFIG{SFGATEID} = '';
        }

        &ask_for('UNIXDOMAINSOCKETS',
                 qq[\nSFgate-server runs on the same host as your cgi-scripts],
                 q[y]);

        if ($::CONFIG{UNIXDOMAINSOCKETS} =~ /^y/i) {
            $::CONFIG{UNIXDOMAINSOCKETS} = 'y';
        }
        else {
            $::CONFIG{UNIXDOMAINSOCKETS} = 'n';
            $::CONFIG{CFLAGS} = '-D INSOCKET';
            &ask_for('SERVERHOST',
                     qq[\nOn which host shall SFgate-server run],
                     q[localhost]);
            &ask_for('SERVERPORT',
                     qq[\nOn which port shall the SFgate-server listen],
                     q[2100]);
            while ($::CONFIG{SERVERPORT} !~ /^\d+$/) {
                &ask_for('SERVERPORT',
                         qq[\nI do not understand. What port],
                         q[2100]);
            }
            if ($::CONFIG{SERVERHOST} ne localhost) {
                print <<"EOF";
                
You should provide a wrapper to
$::CONFIG{STARTSERVER}
to ensure that the server is startet automatically via the SFgate client.
EOF
;
                $::CONFIG{STARTSERVER} .= '.start';
                &ask_for('STARTSERVER',
                         qq[Which wrapper should be called to automatically ]
                         . qq[start the server on $::CONFIG{SERVERHOST}]);
            }
        }
    }
    else {
        $::CONFIG{USESERVER} = 'n';
        $::CONFIG{STARTSERVER} = 'SFgate';
    }
    
    # Logfile locations
    print <<"EOF";
                
SFgate does some logging on queries, error messages etc. Therefore
it needs to write a log file. Note that SFgate needs file create
and write permissions in the specified directory!
EOF
;
    &ask_for('LOGDIR',
             qq[In which directory should the logfiles go],
             q[/home/robots/www/log/SFgate]);
    $::CONFIG{LOGFILE} = "$::CONFIG{LOGDIR}/SFgate$::CONFIG{SFGATEID}.log";
    print "will write SFgate logs to $::CONFIG{LOGFILE}\n";

    if ($::CONFIG{USESERVER} eq 'y') {
        my $suffix = $::CONFIG{SFGATEID};
        $::CONFIG{LOGSERVER} = "$::CONFIG{LOGDIR}/SFgate-server$suffix.log";
        print "will write SFgate-server logs to $::CONFIG{LOGSERVER}\n";
        $::CONFIG{LOGSERVERERROR} = "$::CONFIG{LOGDIR}/SFgate-server$suffix.error";
        print "will write SFgate-server error messages to $::CONFIG{LOGSERVERERROR}\n";
        $::CONFIG{LOGCLIENT} = "$::CONFIG{LOGDIR}/SFgate-client$suffix.log";
        print "will write SFgate-client logs to $::CONFIG{LOGCLIENT}\n";
        if ($::CONFIG{UNIXDOMAINSOCKETS} eq 'y') {
            $::CONFIG{SOCKFILE} = "$::CONFIG{LOGDIR}/SFgate-server$suffix.socket";
            print "will use $::CONFIG{SOCKFILE} as socket file\n";
        }
    }
    print "\n";
    
    ##
    ## end question section
    ##

    &writeconfig;

    &register unless $ARG{show};  # register
    
    # postcard
    &postcard;

    print <<"EOF";
Continue with
    make
    make test
    make install
to do the obvious.

EOF
;
    
}


sub readconfig
{
    open(IN, "< $configfile") || die "Couldn't open $configfile: $!\n";

    local($_);
    while (<IN>) {
        chomp;
        ($key, $value) = split('=', $_, 2);
        $value =~ s/^'|'$//g;
        $::CONFIG{$key} = $value;
    }
}


sub writeconfig
{
    open(OUT, "> $configfile") || die "Couldn't open $configfile: $!\n";

    local($_);
    foreach (sort(keys %::CONFIG)) {
        printf OUT "%s='%s'\n", $_, $::CONFIG{$_};
    }
    
    close(OUT); 
}


sub ask_for
{
    my ($what, $question, $default) = @_;
    my $answer;

    $default = $::CONFIG{$what} || $default;
    
    print "$question\n [$default]? ";

    if ($ARG{show}) {
        print "$default\n";
    }
    else {
        $answer = <STDIN>;
        chomp($answer);
    }

    $answer = $answer || $default;
    $answer = '' if $answer eq 'none';

    $::CONFIG{$what} = $answer;

}


sub get_revision
{
    my($version, $revision);
    open(PATCH, "./patchlevel.h") || die "Couldn't open ./patchlevel.h: $!\n";
    while (<PATCH>) {
        if (/VERSION ([\d.]+)/) {
            $version = $1;
        }
        if (/PATCHLEVEL (\d+)/) {
            $revision = $1;
        }
    }

    sprintf("%5.3f", $version + $revision/1000);
}


sub register
{
    print <<"EOF";
    
To get an idea of how often and where SFgate is used we would like
you to send us a registration mail. Note that this will *never*
become a licensing scheme or some crazy thing like that. It\'s just
our curiosity.

EOF
;

    $address = 'sfgate@ls6.informatik.uni-dortmund.de';

    print "Send registration mail to $address (y/n)[y]? ";
    $answer = <STDIN>;

    if ($answer !~ /^n/i) {
        system "perlbug", "-a", $address, "-C",
            "-s", "Installed SFgate $::CONFIG{REVISION} on $::CONFIG{HOSTNAME}",
            "-f", "config.sh";
    }
    else {
        print "Ok... I will keep your secret!\n";
    }
}


sub postcard
{
    print <<"EOF";

There is a list of some SFgate application forms on 
http://ls6-www.informatik.uni-dortmund.de/ir/projects/SFgate/
If you want your SFgate applications to be listed there, send
a mail with titles and URLs of your applications.

If you like SFgate you may want to flood us with gifts. The first
thing you could do is to send us a picture postcard of your city.
We collect and exhibit them on:
http://ls6-www.informatik.uni-dortmund.de/ir/projects/SFgate/album/
Send your card to the following address:

  Norbert Goevert, Ulrich Pfeifer
  University of Dortmund
    Computer Science Department, LS VI
  August-Schmidt-Strae 12

   D-44221 Dortmund

EOF
;
}


sub main::replace
{
    my $outfile = shift;
    my $file    = shift;
    
    open(IN, "< $file")      || die "Couldn't open $file: $!\n";
    open(OUT, "> $outfile" ) || die "Couldn't open $outfile: $!\n";
    
    local($_);
    while (<IN>) {
        s/\@([A-Z_]+)\@/$::CONFIG{$1}/g;
        print OUT;
    }
  
    close(IN);
    close(OUT);
}
