#  Copyright (c) 1997-2006
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
#  http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.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,v 1.3.2.1 2006/03/14 16:20:56 gawrilow Exp $

use strict;

# the regex'es here must be always kept in sync with the main script perl/polymake

my $bindir=shift;
-d $bindir or die "target directory \"$bindir\" does not exist\n";

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

if (my ($perl)= $ARGV[0] =~ /^PerlExe=(.*)/) {
   s/^#!\S+/#!$perl/s;
   shift;
}
s/^sub find_build_dir .*?^\}\n+//ms;

my $prefix;
if (($prefix)= $ARGV[0] =~ /^PREFIX=(.*)/) {
   my ($tail)=rindex($bindir,$1)+length($1);
   $tail=substr($bindir,$tail)."/polymake";
   shift;
   s|(Install\w+=)$prefix|$1\$PREFIX| for (@ARGV);
   $prefix="   my (\$PREFIX)= \$0 =~ m{^(.*)$tail};\n";
}

my $vars=join("", map { s/=/="/; "   \$$_\";\n" } @ARGV);
s/^\s*\$InstallTop=.*?\n\n/$prefix$vars\n/ms;

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

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


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