#!/usr/bin/perl -w 
# Need to specify the full path of Perl above


use strict;


BEGIN {
    # On Ubuntu 18.04, gsdlCGI.pm can't be found as the cgi folder is not among @INC paths.
    # Ensure gsdlCGI.pm is available in @INC by adding the cgi folder to it.
    # For GS2:
    my $gsdl_cgi_path = $ENV{'GSDLHOME'} . "/cgi-bin";
    # For GS3:
    $gsdl_cgi_path = $ENV{'GSDL3HOME'} . "/WEB-INF" . "/cgi" if defined $ENV{'GSDL3HOME'};

    my $found_cgi_path = 0;
    foreach my $inc_path (@INC) {
        if($inc_path eq $gsdl_cgi_path) {
                $found_cgi_path = 1;
                last;
        }
    }
    if(!$found_cgi_path) {
      unshift (@INC, $gsdl_cgi_path);
    }
}


# Set this to 1 to work around IIS 6 craziness
my $iis6_mode = 0;


# IIS 6: for some reason, IIS runs this script with the working directory set to the Greenstone
#   directory rather than the cgi-bin directory, causing lots of stuff to fail
if ($iis6_mode)
{
    # Change into cgi-bin\<OS> directory
    chdir("cgi-bin");
    if(defined $ENV{'GSDLARCH'}) {
	chdir($ENV{'GSDLOS'}.$ENV{'GSDLARCH'});
    } else {
	chdir($ENV{'GSDLOS'});
    }
}


# We use require and an eval here (instead of "use") to catch any errors loading the module (for IIS)
eval("require \"gsdlCGI.pm\"");
if ($@)
{
    print STDOUT "Content-type:text/plain\n\n";
    print STDOUT "ERROR: $@\n";
    exit 0;
}



sub main
{
    my $gsdl_cgi = new gsdlCGI();

    # Load the Greenstone modules that we need to use
    $gsdl_cgi->setup_gsdl();

    my $gsdlhome = $ENV{'GSDLHOME'};
    $gsdl_cgi->checked_chdir($gsdlhome);

    require cgiactions::imageaction;

    $gsdl_cgi->parse_cgi_args();

    # We don't want the gsdlCGI module to return errors and warnings in XML
    $gsdl_cgi->{'xml'} = 0;

    my $action = new imageaction($gsdl_cgi,$iis6_mode);

    $action->do_action();
}




&main();
