# Klaras Connect for EPrints
#
# Copied into this archive's cfg/cfg.d/ when the package is enabled
# (Admin > EPrints Bazaar), removed when it is disabled. Settings that a
# librarian changes live in the database, on the "Klaras Connect" screen,
# not in this file.

# Screens and the indexer job. Bazaar plugins are disabled until a
# repository enables them here.
$c->{plugins}->{'Screen::Admin::KlarasConnect'}->{params}->{disable} = 0;
$c->{plugins}->{'Screen::Admin::KlarasHealth'}->{params}->{disable} = 0;
$c->{plugins}->{'Screen::Admin::KlarasUsage'}->{params}->{disable} = 0;
$c->{plugins}->{'Event::KlarasConnect'}->{params}->{disable} = 0;

# Development only. Never set these on a production repository.
# $c->{klaras_connect}->{panel_url} = 'http://localhost:8000';
# $c->{klaras_connect}->{development} = 1;
#
# Behind a reverse proxy, list its address so the real client IP is used
# for rate limiting (X-Forwarded-For is ignored otherwise):
# $c->{klaras_connect}->{trusted_proxies} = [ '10.0.0.5' ];

# Route /klaras/connect/v1/* and /klaras/source/v1/* to the plugin's
# handler, exactly like EPrints routes its own /rest. Every other URL is
# left untouched. If the plugin's modules cannot load (a broken upgrade,
# a missing Perl module), the routes answer 503 and the rest of the
# repository keeps working.
{
	my $loaded;
	my $load_error;

	$c->add_trigger( EPrints::Const::EP_TRIGGER_URL_REWRITE, sub {
		my( %params ) = @_;

		my $uri = $params{uri};
		my $urlpath = defined $params{urlpath} ? $params{urlpath} : '';
		return EPrints::Const::EP_TRIGGER_OK if !defined $uri;
		return EPrints::Const::EP_TRIGGER_OK if index( $uri, $urlpath . '/klaras/' ) != 0;

		my $path = substr( $uri, length $urlpath );
		return EPrints::Const::EP_TRIGGER_OK if $path !~ m{\A/klaras/(?:connect|source)/v1(?:/[A-Za-z0-9/_-]*)?\z};

		my $r = $params{request};

		if( !defined $loaded )
		{
			$loaded = eval { require EPrints::KlarasConnect::Handler; 1 } ? 1 : 0;
			$load_error = $@ if !$loaded;
		}

		$r->handler( 'perl-script' );
		$r->set_handlers( PerlMapToStorageHandler => sub { EPrints::Apache::AnApache::OK() } );

		if( $loaded )
		{
			$r->pnotes( klaras_connect_path => $path );
			$r->set_handlers( PerlResponseHandler => \&EPrints::KlarasConnect::Handler::handler );
		}
		else
		{
			my $err = $load_error;
			$r->set_handlers( PerlResponseHandler => sub {
				my( $req ) = @_;
				my $repo = $EPrints::HANDLE->current_repository;
				$repo->log( "klaras_connect: plugin could not load: $err" ) if defined $repo;
				$req->status( 503 );
				$req->content_type( 'application/json; charset=utf-8' );
				$req->print( '{"error":{"code":"unavailable","message":"Klaras Connect sedang tidak tersedia."},"meta":{"api_version":"1"}}' );
				return EPrints::Apache::AnApache::OK();
			} );
		}

		${ $params{return_code} } = EPrints::Apache::AnApache::OK();
		return EPrints::Const::EP_TRIGGER_DONE;
	}, priority => 100 );
}

