#!/bin/sh

if [ $# -lt 3 ]; then
	echo "Usage: $0 provides/requires <datadir> <controldir> [version]" >&2
	exit 1
fi

subcmd="$1"
datadir="$2"
controldir="$3"
pversion="$4"

[ ! -d "$datadir" ] && exit 0

mkdir -p "$controldir"

ocamldeps=/usr/lib/rpm/ocamldeps.sh

case "$subcmd" in
provides)
	ocaml_providers="$(find "$datadir" -type f \( \
		-name '*.cma' -o -name '*.cmi' -o -name '*.cmo' \
		-o -name '*.cmx' -o -name '*.cmxa' \) 2>/dev/null \
		| $ocamldeps --provides \
		| sed -e 's/^ocaml(/ocaml4-intf:/' \
			-e 's/^ocamlx(/ocaml4-impl:/' \
			-e 's/) = /:/')"

	for prov in $ocaml_providers; do
		if [ "$pversion" ]; then
			echo "$prov=$pversion" >> "$controldir"/.provides-py
		else
			echo "$prov" >> "$controldir"/.provides-py
		fi
	done
;;
requires)
	ocaml_deps="$(find "$datadir" -type f \( \
		-name '*.cma' -o -name '*.cmi' -o -name '*.cmo' \
		-o -name '*.cmx' -o -name '*.cmxa' \) 2>/dev/null \
		| $ocamldeps --requires \
		| sed -e 's/^ocaml(/ocaml4-intf:/' \
			-e 's/^ocamlx(/ocaml4-impl:/' \
			-e 's/) = /:/')"

	for dep in $ocaml_deps; do
		grep -Fsq "$dep" "$controldir"/.provides-py \
		|| echo "$dep" >> "$controldir"/.python3-needs
	done
;;
*)
	echo "Invalid subcmd" >&2
	exit 1
;;
esac
