#!/usr/bin/perl -w
# -*- perl -*-

#######
# I wrote this script to be able to move the browser beween my home
# computer (development) and work where the files are actually
# used. The main difference is that the perl distribution I have at
# home is more recent and contains more modules.
#
#######
#  How to run installation script
#
# Type:
# perl install.pl
#
#######

$| = 1 ; # Wonderful perl syntax for turning output buffering off!

## find out of we have CGI.pm
#
my $c = "CGI" ;

eval "use $c;"  ;
my $gotCGI =  $@ eq "" ;

if($gotCGI) {
    print "We have the $c module\n" ;
}
else {
    die "CGI.pm module not present. Download from http://www.cpan.org/ !" ; 
} ;

## find perl
#
my $perl = &pathToApp("perl") ;

if(defined $perl and $perl ne "") {
    print "Perl: $perl\n" ;
}
else {
    die "Can not find perl in PATH!\n" ;
} ;

## Ask operator to confirm
#
my $p =`pwd` ;
chomp $p ;

while(1) {
    print "\n\nOK to install cgi bins in $p? [y/n] " ;
    $_ = <STDIN>;
    chomp ;
    my $a = uc $_ ;
    $a eq "Y" and do { last ; };
    $a eq "N" and die "Aborted"; 
    print "Answer 'y' or 'n'." ;
}

				# Make sure we can open cgi_files.tar
unless( -r "cgi_files.tar") { die "Can not open \"cgi_files.tar\" for read." ; } ;

				# Get file list and filter out .cgi, .pl and .perl
local *P ;
open(P,"tar -tf cgi_files.tar|") or die "Can not read \"cgi_files.tar\"" ;
my @perlfiles ;
while(<P>) {
    chomp ;
    (/\.cgi$/ or /\.pl/ or /\.perl/) and do { push @perlfiles,$_ ; } ;
}
close P ;

				# Extract files and make writeable
system("tar xvf cgi_files.tar") ;
chmod 0755,@perlfiles ;

				# Change first line of all files to point to
				# perl
my $f ;
foreach $f (@perlfiles) {
    # Read file
    open(P,"<$f") ;
    my @file=<P> ;
    close P ;
    # Change first line  
    $file[0]="#!$perl -w\n" ; 
    # Write file
    open(P,">$f") ;
    print P @file ;
    close P ;    
}
chmod 0755,@perlfiles ;

				# Clean up
unlink "cgi_files.tar" ;


################ SUBROUTINES ################
###
### Find path to an app ("type -path" does not work on all systems")
###
sub pathToApp($)
{
    my $app = shift @_ ;
    my $result ;
    my $p ;
    foreach $p (split(':',$ENV{"PATH"} )) {
	$p =~ s|/$|| ;
	if(-x "$p/$app") {
	    $result = "$p/$app" ;
	}
    }
    return $result ;
} ;





