#!/usr/bin/env bash
# Copyright 1999-2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

source "${PORTAGE_BIN_PATH}"/isolated-functions.sh || exit 1

if [[ -z ${PORTAGE_INTERNAL_DOLIB} ]] && ! ___eapi_has_dolib_libopts; then
	die "'${0##*/}' has been banned for EAPI '${EAPI}'"
	exit 1
fi

if ! ___eapi_has_prefix_variables; then
	ED=${D}
fi

if ! ___eapi_has_DESTTREE_INSDESTTREE; then
	[[ -n ${DESTTREE} ]] &&
		die "${0##*/}: \${DESTTREE} has been banned for EAPI '${EAPI}'; use 'into' instead"
else
	# backwards compatibility
	__E_DESTTREE=${DESTTREE}
fi

# Setup ABI cruft
libdir="lib"
libdir_var="LIBDIR_${ABI}"
if [[ -n ${ABI} && -n ${!libdir_var} ]] ; then
	libdir=${!libdir_var}
fi

libdir="${ED%/}/${__E_DESTTREE#/}/${libdir}"

if [[ $# -lt 1 ]] ; then
	__helpers_die "${0##*/}: at least one argument needed"
	exit 1
fi
if [[ ! -d ${libdir} ]] ; then
	install -d "${libdir}" || { __helpers_die "${0##*/}: failed to install ${libdir}"; exit 1; }
fi

ret=0

for x in "$@" ; do
	if [[ -e ${x} ]] ; then
		if [[ ! -L ${x} ]] ; then
			install ${LIBOPTIONS} "${x}" "${libdir}"
		else
			ln -s "$(readlink "${x}")" "${libdir}/${x##*/}"
		fi
	else
		echo "!!! ${0##*/}: ${x} does not exist" 1>&2
		false
	fi
	((ret|=$?))
done

[[ ${ret} -ne 0 ]] && __helpers_die "${0##*/} failed"
exit ${ret}
