#! /usr/bin/perl -T

# Script to generate 'Page not found' error page in case that URL exceeds
# the maximum number of page levels properly processed by the rest of
# the cgi-bin scripts.
#
# In ascending order of page levels:
#   1 - tables.pl (ground level, './')
#   2 - db.pl
#   3 - modify.pl
#   4 - image.pl
#   5 and more - notfound.pl

my $dir;
BEGIN {
    use Cwd qw(abs_path);
    $dir = abs_path(__FILE__);
    $dir =~ /(.*)(\/.*\/.*\/.*\..*)$/;
    $dir = $1;
    unshift(@INC, $dir . "/lib");
}

use strict;
use warnings;
use CGI qw(:standard -nosticky -utf8 start_div end_div);

use CGIParameters qw( read_cgi_parameters);
use HTMLGenerator qw( error_page );
use RestfulDB::CGI qw( save_cgi_parameters );
use RestfulDB::Defaults qw( get_css_styles get_default_cgi_parameters );
use RestfulDB::DBSettings qw( get_database_settings );
use RestfulDB::Exception;

# STDIN must NOT be set to binmode "UTF-8", since CGI with the '-utf8'
# flag handles this.
binmode( STDOUT, "utf8" );
binmode( STDERR, "utf8" );

$ENV{PATH} = ""; # Untaint and clean PATH

my $base_uri = $ENV{REQUEST_URI};
$base_uri =~ s/\?.*$//;

my $cgi = new CGI;
my $format = 'html';

my( $start_level, $extra_level_count );

eval {

    my %local_CGI_parameters = (
        suffix => { re => '.*' },
        starting_level => { re => '^[0-9]+$' },
    );

    my( $params, $changed );
    eval {
        ( $params, $changed ) =
            read_cgi_parameters( $cgi,
                                 { %local_CGI_parameters } );
    };
    InputException->throw( $@ ) if $@;

    $format = $params->{format} if $changed->{format};

    my $suffix = $params->{suffix};
    $start_level = $params->{starting_level};
    $extra_level_count = 0;

    while ( $suffix =~ /\//g ) {
        $extra_level_count++;
    }

    RecordNotFoundException->throw( 'Page not found at requested base URL: ' .
                                    $base_uri );
};

if( $@ ) {
    error_page( $cgi, $@, ($start_level + $extra_level_count) );
}
