#!/usr/bin/perl -w
# installer: enter working directory into Perl script
# usage: installer file [file2 ..]
# 20050912 erikt@science.uva.nl

use Cwd;

$command = $0;
# get current working directory
$cwd = cwd();
# get location of perl
open(INFILE,"which perl |") or die "$command: cannot run which\n";
$perl = <INFILE>;
if (not defined $perl) { die "$command: cannot find Perl\n"; }
chomp($perl);
close(INFILE);

foreach $file (@ARGV) {
   if (not open(INFILE,$file)) {
      print STDERR "$command: warning: cannot open $file\n";
      next;
   }
   $tmpfile = &makeFilename();
   open(OUTFILE,">$tmpfile") or 
      die "$command: cannot open $tmpfile for writing\n";
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      if ($line =~ /BASEDIR\s*=/) { 
         $line =~ s?=.*?=\"$cwd\"?;
      } elsif ($line =~ /baseDir\s*=/i) { 
         $line =~ s?=.*?= \"$cwd\";?;
      } elsif ($line =~ /^\#!.*perl/) {
         $line = "\#!$perl -w";
      }
      print OUTFILE "$line\n"; 
   }
   close(OUTFILE);
   close(INFILE);
   unlink($file);
   system("mv $tmpfile $file");
   system("chmod 555 $file");
}

exit(0);

sub makeFilename() {
   my ($filename,$random);

   # make random file name
   srand(time^($$+($$<<15)));
   $random = int(rand(65536));
   $filename = "installer.$$.$random";
   while (open(FILE,"$filename")) {
      # file exists
      close(FILE);
      $random = int(rand(65536));
      $filename = "installer.$$.$random"; # create other file name
   }
   return($filename);
}
