#!/usr/bin/perl -w

use strict;
use warnings;
use Carp;
use utf8;
use lib "/var/www/tuneportals2";

use Log::Log4perl;
my $log_conf_file = "/var/www/tuneportals2/log4perl.conf";
Log::Log4perl->init_once($log_conf_file);
my $log = Log::Log4perl::get_logger();

use Tuneportals;
use Exception::Class;
use Try::Tiny;

# the Tuneportals class will determine the correct subclass for this request
# any errors will be caught and displayed through the fatal_error method
my $site;
#eval { 
	$site = Tuneportals->new; 
	if (!$site) {
		use Data::Dumper;
		warn(Dumper(Tuneportals->new));
	}
#};
#if ($@) {
#	Tuneportals->fatal_error($@);
#}

# this looks complicated but isn't really.
# first we try to display the request
# if there are any errors they are caught and handled by the object's fatal_error method
# if that fails, errors are caught and handled by the class's fatal_error method instead
# 10-12-2011 JSN - put a hedge against calling $site->run on an undefined site object - reduce error logging
my $results = eval {
	if ($site)
	{
		my $results = eval {
			try {
				$site->run;
				1;
			}
			catch {
				if ( ref($_) eq 'SCALAR' || !$_->can('rethrow') ) {
					$site->fatal_error("caught regular failure - $_");
				} elsif ( blessed $_ && $_->isa('Exception::Class::Base') ) {
					$site->fatal_error( "caught exception - " . $_->as_string . ", " . $_->trace );
				} else {
					$site->fatal_error( "unknown error - " . $_ );
				}
				# Handled. fatal_error() returns empty, and try() hands back the
				# catch block's value, so without this $results is false and the
				# fallback below renders a SECOND error page with an empty $@
				# ("An unspecified error has occurred"). If fatal_error itself
				# dies we never get here, and the fallback still runs.
				1;
			}
		};
		if ( !$results ) {
			if ( my $e = Exception::Class->caught('Tuneportals::Exception::Atom') ) {
				$site->fatal_error( $e->as_string . " - " . $e->trace );
			} else {
				$site->fatal_error($@);
			}
		}
	} else {
		use Data::Dumper;
		warn( "No site obj" );
	}
	1;
};
if ( $@ || !$results ) {
	Tuneportals->fatal_error($@);
}

