#!/usr/local/bin/perl

use lib qw(./lib);
use Apache::ASP;

# help section
use File::Basename;
use Getopt::Std;
use Cwd;
use Carp qw(confess);

$SIG{__DIE__} = \&confess;
getopts('hsdbo:p:');

#if($ENV{GATEWAY_INTERFACE} =~ /cgi/i) {
#    if(-e $ENV{PATH_TRANSLATED}) {
#	push(@ARGV, $ENV{PATH_TRANSLATED});
#    } else {
#	die("no file to parse");
#    }
#}

if($opt_h || ! @ARGV) {
    print <<HELP;
Usage: asp [-hsdb] [-o directory] file1 \@arguments file2 \@arguments ...

    -h  Help you are getting now!
    -s  Setup \$Session and \$Application state for script.
    -d  Set to debug code upon errors.
    -b  Only return body of document, no headers.
    -o  Output directory, writes to files there instead of STDOUT
    -p  GlobalPackage config, what perl package are the scripts compiled in.

This program will run asp scripts from the command line.
Each file that is specified will be run, and the 
\$Request->QueryString() and \$Request->Form() data will be 
initialized by the \@arguments following the script file name.  

The \@arguments will be written as space separated 
words, and will be initialized as an associate array where
%arguments = \@arguments.  As an example:

 asp file.asp key1 value1 key2 value2

would be similar to calling the file.asp in a web environment like

 /file.asp?key1=value1&key2=value2

HELP
    ;
    exit;
}

if($opt_o && ! -e $opt_o) {
    mkdir($opt_o, 0750) || die("can't mkdir $opt_o");    
}

$Config = '';
if(-e 'asp.config') {
    # read in .asp to load %Config
    open(CONFIG, 'asp.config') || die("can't open .asp: $!");
    $Config = join('', <CONFIG>);
    close CONFIG;
}

my $cwd = cwd();
while(@ARGV) {
    $cwd && (chdir($cwd) || die("can't chdir to $cwd"));
    my $file = shift @ARGV;
    my @script_args;

    unless(-e $file) {
	print "file $file does not exist\n";
	next;
    }

    while(@ARGV) {
	last if(-e $ARGV[0]);
	push(@script_args, shift @ARGV);
    }
	
    if($opt_o) {
	my $basename = basename($file);
	open(STDOUT, ">$opt_o/$basename") || die("can't open $opt_o/$basename for writing");
    }

    $r = &Apache::ASP::CGI::init($file, @script_args);
    $0 = $file; # might need real $0 in $Config
    eval $Config;
    $@ && die("can't eval config error: $@");

    $r->dir_config('NoState', 0) if $opt_s;
    if($opt_d) {
	$r->dir_config('Debug', -3);
	$r->dir_config('CommandLine', 1);
    }
    if($opt_b) {
	$r->dir_config('NoHeaders', 1);
    }
    if($opt_p) {
	$r->dir_config('GlobalPackage', $opt_p);
    }

    for(keys %Config) {
	$r->dir_config($_, $Config{$_});
    }

    &Apache::ASP::handler($r);

    if($opt_o) {
	close STDOUT;
    }
    
}


