#!@SH@
#
# opkhelper
# src/oh-shlibdeps.sh
# Find shared library dependencies.
#
# Copyright (C) 2019  Patrick "P. J." McDermott
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. '@pkgdatadir@/load.sm'
. '@LIBOPKBUILD@'

READELF_NEEDED_SED='s/^ 0x[0-9a-f]* (NEEDED) *Shared library: \[\(.*\)\]$/\1/p'

find_lib()
{
	local lib="${1}"
	shift 1
	local rtld_dirs=
	local pkg=
	local dir=

	if [ '@multiarch_libdir@' = 'yes' ]; then
		rtld_dirs="/lib/${OPK_HOST_ARCH} /usr/lib/${OPK_HOST_ARCH}"
	else
		rtld_dirs='/lib /usr/lib'
	fi

	# Check just-built packages.
	for pkg in *.data/; do
		for dir in ${rtld_dirs}; do
			if [ -r "${pkg}/${dir}/${lib}" ]; then
				if command -V ob_qualify_package_name \
						1>/dev/null 2>/dev/null; then
					pkg="$(ob_qualify_package_name \
						"${pkg%.data/}" \
						"${OPK_HOST_ARCH}")"
				else
					pkg="${pkg%.data/}"
				fi
				printf '%s,\n' "${pkg}"
				return 0
			fi
		done
	done

	# Check installed packages.
	for dir in ${rtld_dirs}; do
		if [ -r "${dir}/${lib}" ]; then
			lib="${dir}/${lib}"
			pkg="$('@OPKG@' search "${lib}" | sed 's/ - .*$//')"
			if [ -n "${pkg}" ]; then
				printf '%s,\n' "${pkg}"
				return 0
			else
				oh_warn "$(oh_get_msg 'shlib_no_pkg')" "${lib}"
				return 0
			fi
		fi
	done

	oh_warn "$(oh_get_msg 'shlib_no_lib')" "${lib}"
	return 0
}

find_needed()
{
	local elf="${1}"
	shift 1

	while IFS='' read -r lib; do
		find_lib "${lib}"
	done <<-EOF
		$('@READELF@' -d "${elf}" | sed -n "${READELF_NEEDED_SED}")
		EOF

	return 0
}

find_elves()
{
	local d="${1}"
	shift 1
	local file=

	while IFS='' read -r file; do
		if file "${file}" | grep -E 'ELF.*(executable|shared)' \
				>/dev/null 2>&1; then
			find_needed "${file}"
		fi
	done <<-EOF
		$(find "${d}" -type f -a ! -path '*/debug/*' \
			-a \( -name '*.so*' -o -perm '-a+x' \))
		EOF

	return 0
}

main()
{
	local d=

	oh_init
	ob_init_package '..' || return 1

	for d in *.data/; do
		exec 3>>"${d%.data/}.substvars"
		printf 'Shlib-Depends:' >&3
		printf ' %s' $(find_elves "${d}" | sort -u) >&3
		printf '\n' >&3
		exec 3>&-
	done

	return 0
}

main "${@}"