#!/usr/bin/perl

# php-ext-info - query the metadata of a PIE (PHP Installer for Extensions)
# source tree
#
# A PIE source tree has composer.json at the top with "type" set to "php-ext"
# or "php-ext-zend", and the extension sources next to it or below
# "php-ext"."build-path".  The PECL layout (package.xml next to a
# <name>-<release> directory) is only detected here; pkg-pecl.mk and
# php-versions read package.xml themselves.

use strict;
use warnings;

use JSON::PP;

my $COMPOSER_JSON = 'composer.json';

sub usage {
	print STDERR <<'EOF';
Usage: php-ext-info [-C <directory>] <query> [<argument>...]

Queries:
  layout              pie, pecl or none
  name                Composer package name (vendor/name)
  extension-name      name of the extension as PHP knows it
  extension-type      php or zend
  priority            priority of the .ini file
  build-path          directory with config.m4, relative to the top
  depends             required extensions (ext-* in "require")
  suggests            suggested extensions (ext-* in "suggest")
  supports <X.Y>...   print those PHP versions that "require"."php" admits
  ini                 print the .ini file enabling the extension

All queries but layout need the pie layout.
EOF
	exit 2;
}

sub fail {
	print STDERR "php-ext-info: @_\n";
	exit 2;
}

sub load_composer {
	return undef unless -f $COMPOSER_JSON;
	open(my $fh, '<', $COMPOSER_JSON) or fail("cannot read $COMPOSER_JSON: $!");
	local $/;
	my $text = <$fh>;
	close($fh);
	my $data = eval { JSON::PP->new->utf8->relaxed->decode($text) };
	fail("cannot parse $COMPOSER_JSON: $@") if $@;
	fail("$COMPOSER_JSON is not a JSON object") unless ref($data) eq 'HASH';
	return $data;
}

sub is_extension {
	my ($composer) = @_;
	return ($composer->{type} // '') =~ /^php-ext(-zend)?$/;
}

# The <name>-<release> directories that package.xml and its per PHP version
# variants point to
sub pecl_source_dirs {
	my @dirs;
	foreach my $xml (sort glob('package.xml package-*.xml')) {
		next unless -f $xml;
		open(my $fh, '-|', 'sh', '-c', 'xml2 < "$1" 2>/dev/null', 'sh', $xml) or next;
		my ($name, $release);
		while (my $line = <$fh>) {
			chomp $line;
			$name    //= $1 if $line =~ m{^/package/name=(.*)$};
			$release //= $1 if $line =~ m{^/package/version/release=(.*)$};
		}
		close($fh);
		next unless defined $name && defined $release;
		push @dirs, "$name-$release" if -d "$name-$release";
	}
	return @dirs;
}

sub layout {
	my ($composer) = @_;
	return 'pecl' if pecl_source_dirs();
	return 'pie' if $composer && is_extension($composer);
	return 'none';
}

sub extension_name {
	my ($composer) = @_;
	my $name = $composer->{'php-ext'}{'extension-name'};
	if (!defined $name || $name eq '') {
		$name = $composer->{name} // '';
		$name =~ s{^.*/}{};
	}
	$name =~ s/^ext-//;
	fail("cannot find a valid extension name in $COMPOSER_JSON")
	    unless $name =~ /^[A-Za-z][A-Za-z0-9_]+$/;
	return $name;
}

sub extension_type {
	my ($composer) = @_;
	return $composer->{type} eq 'php-ext-zend' ? 'zend' : 'php';
}

sub priority {
	my ($composer) = @_;
	my $priority = $composer->{'php-ext'}{priority} // 80;
	fail("invalid priority '$priority' in $COMPOSER_JSON") unless $priority =~ /^[0-9]+$/;
	return $priority;
}

sub upstream_version {
	my $version = qx(dpkg-parsechangelog -SVersion 2>/dev/null) // '';
	chomp $version;
	$version =~ s/^[0-9]+://;
	$version =~ s/-[^-]*$//;
	return $version;
}

sub build_path {
	my ($composer) = @_;
	my $path = $composer->{'php-ext'}{'build-path'} // '';
	if ($path =~ /\{version\}/) {
		my $version = upstream_version();
		fail("cannot expand {version} in build-path without debian/changelog") if $version eq '';
		$path =~ s/\{version\}/$version/g;
	}
	$path =~ s{/+$}{};
	fail("build-path '$path' must be relative and must not contain '..'")
	    if $path =~ m{^/} || grep { $_ eq '..' } split(m{/}, $path);
	return $path;
}

# Extensions from one of the Composer link sections, the way they appear in
# Debian package names
sub extensions {
	my ($composer, $section) = @_;
	my $links = $composer->{$section};
	return () unless ref($links) eq 'HASH';
	my %exts;
	foreach my $key (keys %{$links}) {
		next unless $key =~ /^ext-(.+)$/i;
		my $ext = lc $1;
		$ext =~ tr/_/-/;
		$exts{$ext} = 1;
	}
	return sort keys %exts;
}

#
# Composer version constraints, reduced to what is needed to tell whether a
# PHP X.Y series is supported.  Versions are [major, minor, patch] and ranges
# are [low, high) with undef for an open end.
#

my $OPERATORS = qr/>=|<=|!=|<>|==|=|>|<|\^|~>|~/;

sub vcmp {
	my ($a, $b) = @_;
	foreach my $i (0 .. 2) {
		my $cmp = $a->[$i] <=> $b->[$i];
		return $cmp if $cmp;
	}
	return 0;
}

sub pad {
	my @v = @_;
	push @v, 0 while @v < 3;
	return [ @v[0 .. 2] ];
}

sub after {
	my ($v) = @_;
	return [ $v->[0], $v->[1], $v->[2] + 1 ];
}

sub bump {
	my @v = @_;
	$v[-1]++;
	return pad(@v);
}

sub parts {
	my ($version) = @_;
	$version =~ s/^v//i;
	return () unless $version =~ /^((?:[0-9]+|[xX*])(?:\.(?:[0-9]+|[xX*]))*)/;
	return split /\./, $1;
}

sub token_range {
	my ($token) = @_;
	$token =~ s/\@[A-Za-z]+$//;
	return (undef, undef) if $token eq '';

	my ($op, $version) = $token =~ /^($OPERATORS)?(.*)$/;
	$op //= '';
	my @parts = parts($version);
	if (!@parts) {
		print STDERR "php-ext-info: ignoring unknown version constraint '$token'\n";
		return (undef, undef);
	}

	# 8.*, 8.1.x
	foreach my $i (0 .. $#parts) {
		next unless $parts[$i] =~ /^[xX*]$/;
		return (undef, undef) if $i == 0;
		my @prefix = @parts[0 .. $i - 1];
		return (pad(@prefix), bump(@prefix));
	}

	my $v = pad(@parts);
	return ($v, undef)        if $op eq '>=';
	return (after($v), undef) if $op eq '>';
	return (undef, $v)        if $op eq '<';
	return (undef, after($v)) if $op eq '<=';
	return (undef, undef)     if $op eq '!=' || $op eq '<>';
	if ($op eq '^') {
		return ($v, [ $v->[0] + 1, 0, 0 ]) if $v->[0] > 0 || @parts == 1;
		return ($v, [ 0, $v->[1] + 1, 0 ]) if $v->[1] > 0 || @parts == 2;
		return ($v, after($v));
	}
	if ($op eq '~' || $op eq '~>') {
		return ($v, [ $v->[0], $v->[1] + 1, 0 ]) if @parts >= 3;
		return ($v, [ $v->[0] + 1, 0, 0 ]);
	}
	return ($v, after($v));
}

sub group_range {
	my ($group) = @_;
	$group =~ s/^\s+|\s+$//g;

	# 8.1 - 8.4
	if ($group =~ /^(\S+)\s+-\s+(\S+)$/) {
		my @low  = parts($1);
		my @high = parts($2);
		if (@low && @high && !grep { /^[xX*]$/ } @low, @high) {
			return (pad(@low), @high >= 3 ? after(pad(@high)) : bump(@high));
		}
	}

	$group =~ s/($OPERATORS)\s+/$1/g;
	my ($low, $high);
	foreach my $token (split /[\s,]+/, $group) {
		my ($l, $h) = token_range($token);
		$low  = $l if defined $l && (!defined $low  || vcmp($l, $low) > 0);
		$high = $h if defined $h && (!defined $high || vcmp($h, $high) < 0);
	}
	return ($low, $high);
}

# Does the constraint admit at least one X.Y.z release?
sub supports {
	my ($constraint, $series) = @_;
	return 1 unless defined $constraint && $constraint =~ /\S/;
	fail("'$series' is not a PHP X.Y version") unless $series =~ /^([0-9]+)\.([0-9]+)$/;
	my $first = [ $1, $2, 0 ];
	my $next  = [ $1, $2 + 1, 0 ];
	foreach my $group (split /\s*\|\|?\s*/, $constraint) {
		my ($low, $high) = group_range($group);
		next if defined $low && defined $high && vcmp($low, $high) >= 0;
		next if defined $low  && vcmp($low, $next) >= 0;
		next if defined $high && vcmp($high, $first) <= 0;
		return 1;
	}
	return 0;
}

usage() unless @ARGV;
if ($ARGV[0] eq '-C') {
	shift @ARGV;
	my $dir = shift @ARGV // usage();
	chdir($dir) or fail("cannot change to $dir: $!");
}
my $query = shift @ARGV // usage();

if ($query eq 'layout') {
	# Whatever sits in composer.json must not break the trees that do not use it
	my $composer = -f $COMPOSER_JSON ? eval {
		open(my $fh, '<', $COMPOSER_JSON) or die "$!\n";
		local $/;
		JSON::PP->new->utf8->relaxed->decode(<$fh>);
	} : undef;
	print STDERR "php-ext-info: ignoring $COMPOSER_JSON: $@" if $@;
	$composer = undef unless ref($composer) eq 'HASH';
	print layout($composer), "\n";
	exit 0;
}

my $composer = load_composer();
fail("no $COMPOSER_JSON with type php-ext or php-ext-zend here")
    unless $composer && is_extension($composer);
$composer->{'php-ext'} = {} unless ref($composer->{'php-ext'}) eq 'HASH';

if ($query eq 'name') {
	print $composer->{name} // '', "\n";
} elsif ($query eq 'extension-name') {
	print extension_name($composer), "\n";
} elsif ($query eq 'extension-type') {
	print extension_type($composer), "\n";
} elsif ($query eq 'priority') {
	print priority($composer), "\n";
} elsif ($query eq 'build-path') {
	print build_path($composer), "\n";
} elsif ($query eq 'depends') {
	print join(' ', extensions($composer, 'require')), "\n";
} elsif ($query eq 'suggests') {
	print join(' ', extensions($composer, 'suggest')), "\n";
} elsif ($query eq 'supports') {
	my $require = ref($composer->{require}) eq 'HASH' ? $composer->{require} : {};
	foreach my $series (@ARGV) {
		print "$series\n" if supports($require->{php}, $series);
	}
} elsif ($query eq 'ini') {
	my $name = extension_name($composer);
	my $directive = extension_type($composer) eq 'zend' ? 'zend_extension' : 'extension';
	print "; configuration for php $name module\n";
	print "; priority=", priority($composer), "\n";
	print "$directive=$name.so\n";
} else {
	usage();
}

exit 0;
