#!/bin/bash
#
# finddeps - find packages that depend on a given depname
#
# SPDX-License-Identifier: GPL-3.0-or-later

_DEVTOOLS_LIBRARY_DIR=${_DEVTOOLS_LIBRARY_DIR:-/usr/share/devtools}
# shellcheck source=src/lib/common.sh
source "${_DEVTOOLS_LIBRARY_DIR}"/lib/common.sh


match=$1

if [[ -z $match ]]; then
	echo 'Usage: finddeps <depname>'
	echo ''
	echo 'Find packages that depend on a given depname.'
	echo 'Run this script from the top-level directory of your ABS tree.'
	echo ''
	exit 1
fi

find . -type d -print0 2>/dev/null| while read -r -d '' d; do
	if [[ -f "$d/PKGBUILD" ]]; then
		pkgname=() depends=() makedepends=() optdepends=()
		# shellcheck source=contrib/makepkg/PKGBUILD.proto
		. "$d/PKGBUILD"
		for dep in "${depends[@]}"; do
			# lose the version comparator, if any
			depname=${dep%%[<>=]*}
			[[ $depname = "$match" ]] && echo "$d (depends)"
		done
		for dep in "${makedepends[@]}"; do
			# lose the version comparator, if any
			depname=${dep%%[<>=]*}
			[[ $depname = "$match" ]] && echo "$d (makedepends)"
		done
		for dep in "${optdepends[@]/:*}"; do
			# lose the version comaparator, if any
			depname=${dep%%[<>=]*}
			[[ $depname = "$match" ]] && echo "$d (optdepends)"
		done
	fi
done
