# Source: https://salsa.debian.org/kernel-team/initramfs-tools
#
# Copyright: 2005 - 2011 maximilian attems <maks@debian.org>
#            2005 Jeff Bailey <jbailey@ubuntu.com>
#            2005 - 2007 David Härdeman <david@hardeman.nu>
#            2008 - 2010 Martin Michlmayr <tbm@cyrius.com>
#            2007 - 2011 Michael Prokop <mika@debian.org>
#            2005 - 2009 Scott James Remnant <scott@ubuntu.com>
#            2009 - 2024 Ben Hutchings <benh@debian.org>
#            2018 - 2024 Benjamin Drung <bdrung@debian.org>
# License: GPL-2+
#  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 package; if not, see 'https://www.gnu.org/licenses/'.

# $1 = file type (for logging)
# $2 = file to copy to initramfs
# $3 (optional) Name for the file on the initramfs
# Location of the image dir is assumed to be $DESTDIR
# If the target exists, we leave it and return 1.
# On any other error, we return >1.
copy_file() {
	local type src target link_target

	type="${1}"
	src="${2}"
	target="${3:-$2}"

	[ -f "${src}" ] || return 2

	if [ -d "${DESTDIR}/${target}" ]; then
		target="${target}/${src##*/}"
	fi

	# Canonicalise usr-merged target directories
	case "${target}" in
	/bin/* | /lib* | /sbin/*) target="/usr${target}" ;;
	esac

	# check if already copied
	[ -e "${DESTDIR}/${target}" ] && return 1

	mkdir -p "${DESTDIR}/${target%/*}"

	if [ -h "${src}" ]; then
		# We don't need to replicate a chain of links completely;
		# just link directly to the ultimate target
		link_target="$(readlink -f "${src}")" || return $(($? + 1))

		# Update source for the copy
		src="${link_target}"

		# Canonicalise usr-merged target directories
		case "${link_target}" in
		/bin/* | /lib* | /sbin/*) link_target="/usr${link_target}" ;;
		esac

		if [ "${link_target}" != "${target}" ]; then
			echo "Add ${type}-link ${target}"

			# Create a relative link so it always points
			# to the right place
			ln -rs "${DESTDIR}/${link_target}" "${DESTDIR}/${target}"
		fi

		# Copy the link target if it doesn't already exist
		target="${link_target}"
		[ -e "${DESTDIR}/${target}" ] && return 0
		mkdir -p "${DESTDIR}/${target%/*}"
	fi

	echo "Add ${type} ${src}"

	cp -pP "${src}" "${DESTDIR}/${target}" || return $(($? + 1))
}
