package EPrints::KlarasConnect::Compat;

# Differences between EPrints releases, found by probing for features
# rather than comparing version numbers. Verified against the 3.3.16 and
# 3.4.7 sources; everything here also exists in 3.3.0+.
#
# Every probe is wrapped so a missing method is a "no", never a die.

use strict;
use warnings;

# Oldest release this plugin is built and tested for.
use constant MIN_VERSION => '3.3.0';

sub eprints_version
{
	my $v = eval { EPrints->human_version };
	if( !defined $v || !length $v )
	{
		my $raw = eval { EPrints->VERSION };
		$v = defined $raw ? ( $raw =~ /^v/ ? substr( $raw, 1 ) : join( '.', map { ord } split //, $raw ) ) : '';
	}
	return $v;
}

# Compares dotted versions numerically: version_cmp('3.4.10', '3.4.7') == 1.
sub version_cmp
{
	my( $x, $y ) = @_;
	my @x = map { /\A([0-9]+)/ ? $1 : 0 } split /\./, ( defined $x ? $x : '0' );
	my @y = map { /\A([0-9]+)/ ? $1 : 0 } split /\./, ( defined $y ? $y : '0' );
	while( @x || @y )
	{
		my $a1 = @x ? shift @x : 0;
		my $b1 = @y ? shift @y : 0;
		return $a1 <=> $b1 if $a1 != $b1;
	}
	return 0;
}

sub is_supported_version
{
	return version_cmp( eprints_version(), MIN_VERSION ) >= 0 ? 1 : 0;
}

sub dataset
{
	my( $repo, $id ) = @_;
	my $ds = eval { $repo->dataset( $id ) };
	$ds = eval { $repo->get_dataset( $id ) } if !defined $ds;
	return $ds;
}

sub has_field
{
	my( $ds, $name ) = @_;
	return 0 if !defined $ds;
	return eval { $ds->has_field( $name ) } ? 1 : 0;
}

# Value of a field, or undef when the field does not exist in this
# repository's schema (schemas differ from one campus to the next).
sub value
{
	my( $obj, $name ) = @_;
	return undef if !defined $obj;
	my $ds = eval { $obj->get_dataset };
	return undef if defined $ds && !has_field( $ds, $name );
	my $v = eval { $obj->value( $name ) };
	return $v;
}

sub has_xapian
{
	my( $repo ) = @_;
	my $plugin = eval { $repo->plugin( 'Search::Xapian' ) };
	return 0 if !defined $plugin;
	return 0 if $plugin->param( 'disable' );
	my $path = eval { $repo->config( 'variables_path' ) };
	return defined $path && -d "$path/xapian" ? 1 : 0;
}

# The indexer touches its tick file every 30 s while it runs.
sub indexer_running
{
	my( $repo ) = @_;
	my $tickfile = eval { require EPrints::Index; EPrints::Index::tickfile() };
	return 0 if !defined $tickfile || !-e $tickfile;
	my $age = time - ( stat( $tickfile ) )[9];
	return $age < 15 * 60 ? 1 : 0;
}

# LWP that can fetch https pages. Enough for the health checks, which read
# the repository's own public pages; the panel, which is sent secrets,
# needs PanelClient::transport, which checks certificates.
sub has_lwp_https
{
	return eval { require LWP::UserAgent; require LWP::Protocol::https; 1 } ? 1 : 0;
}

sub mod_perl_version
{
	return defined $mod_perl2::VERSION ? $mod_perl2::VERSION
		: defined $mod_perl::VERSION ? $mod_perl::VERSION : undef;
}

1;
