#  Copyright (c) 1997-2009
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
#  http://www.polymake.de
#
#  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.
#-------------------------------------------------------------------------------
#  $Project: polymake $$Id: convert_main_script 9362 2009-10-17 22:46:24Z gawrilow $

use strict;
use Getopt::Long qw( GetOptions :config require_order no_ignore_case );
use Config;

my %opts;

if ( !GetOptions(\%opts, 'bindir=s', 'perldir=s', 'prefix=s', 'perllib=s')
     or !exists $opts{bindir} || !-d $opts{bindir}) {
   $!=1;
   die "usage: $0 --bindir DIR [ --perldir DIR --prefix DIR ]\n";
}

undef $/;
open S, "perl/polymake" or die "can't read perl/polymake: $!\n";
$_=<S>;
close S;

if ($^O eq "darwin" && $ENV{ARCHFLAGS} =~ /-arch /) {
   s{^\#!\S+}{#!/usr/bin/arch $ENV{ARCHFLAGS} $Config::Config{perlpath}}s;
} else {
   s{^\#!\S+}{#!$Config::Config{perlpath}}s;
}
my $vars="";

if (exists $opts{prefix}) {
   my $tail=rindex($opts{bindir},$opts{prefix});
   die "prefix does not match bindir\n" if $tail<0;
   $tail=substr($opts{bindir},$tail+length($opts{prefix}))."/polymake";
   $vars="   my (\$PREFIX)= \$0 =~ m{^(.*)$tail};\n";
   s|(Install\w+=)$opts{prefix}|$1\$PREFIX| for (@ARGV);
}

$vars.=join("", map { s/=/="/; "   \$$_\";\n" } @ARGV);
if (exists $opts{perllib}) {
   $vars.="   \@addlibs=qw($opts{perllib});\n";
}
s|(^BEGIN\s*\{\s*\n)(?s:.*?)(^\}\n)|$1$vars$2|m;

unlink "$opts{bindir}/polymake";
open T, ">$opts{bindir}/polymake" or die "can't create $opts{bindir}/polymake: $!\n";
print T;
close T;

chmod(0555, "$opts{bindir}/polymake") or die "chmod $opts{bindir}/polymake failed: $!\n";

=pod
open S, "perllib/Polymake/Config.pm" or die "can't read perllib/Polymake/Config.pm: $!\n";
$_=<S>;
close S;

defined($opts{perldir} ||= $Config::Config{installsitearch})
or die "can't determine the target location for the perl modules\n";

open T, ">$opts{perldir}/Polymake/Config.pm" or die "can't create $opts{perldir}/Polymake/Config.pm: $!\n";
print T;
close T;

chmod(0444, "$opts{perldir}/Polymake/Config.pm") or die "chmod $opts{perldir}/Polymake/Config.pm failed: $!\n";
=cut

# Local Variables:
# mode: perl
# c-basic-offset:3
# End:
