#!/bin/bash
# php-api-requires: RPM dependency generator for PHP extensions.
# Emits Requires: php(zend-abi) = <N> for .so files placed into PHP
# extension directories. Paths come on stdin, one per line.
#
# The number is ZEND_MODULE_API_NO, read from the module build-id
# marker ("API" + number, e.g. API20230831,NTS) embedded in every
# PHP extension binary - the same value the runtime checks when
# loading a module, so the tag reflects what the .so was actually
# built with, not the number recorded in the buildroot headers. Only the module
# API marker is used: the pattern requires 8 digits after "API2" and
# cannot match the Zend extension marker (API420230831) or arbitrary
# "API" substrings. A .so without the marker is not a PHP extension
# and fails the build.
#
# The php(zend-abi) capability is provided by the library packages
# of the PHP versions (lib64php8_common5, lib64php7_common5 in rosa13).

# Exit codes of internal dependency generators are ignored by rpm
# (rpmfc.c: failnonzero = 0), so a fatal error is reported by printing
# a line starting with "!" to stdout: parseRCPOT() rejects such tokens
# and aborts the build with this text as the error message.

fatal() {
	echo "php-api-requires: $1" >&2
	echo "!!! php-api-requires FATAL: $1"
	exit 0
}

declare -A emitted

while IFS= read -r f; do
	# <buildroot>/<libdir>/php*/extensions/<file>.so
	if ! [[ "$f" =~ /php[^/]*/extensions/[^/]+\.so$ ]]; then
		continue
	fi
	api=$(LC_ALL=C grep -aoE 'API2[0-9]{7}' "$f" | head -n1)
	api="${api#API}"
	if [ -z "$api" ]; then
		fatal "no PHP module build-id marker (API2xxxxxxx) in '$f'; this is not a PHP extension binary"
	fi
	# One tag per API number: a directory holding binaries built with
	# different module APIs gets several tags.
	if [ -z "${emitted[$api]:-}" ]; then
		emitted[$api]=1
		echo "php(zend-abi) = $api"
	fi
done
