#!/bin/bash
###############################################################################
#                                                                             #
# IPFire.org - A linux based firewall                                         #
# Copyright (C) 2007-2022  IPFire Team  <info@ipfire.org>                     #
#                                                                             #
# 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 3 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/>.       #
#                                                                             #
###############################################################################

find_rootfile() {
	local path="${1}"
	local package="${2}"

	local file

	for file in "${path}/${arch}/${package}" "${path}/${package}"; do
		if [ -f "${file}" ]; then
			echo "${file}"
			break
		fi
	done
}

descend() {
	local path="${1}"
	shift

	local packages=( "$@" )
	local package
	local file

	# Find all packages
	if [ "${#packages[@]}" -eq 0 ]; then
		for file in "${path}/"* "${path}/${arch}"/*; do
			if [ -f "${file}" ]; then
				packages+=( "${file##*/}" )
			fi
		done
	fi

	# Return the correct rootfile
	for package in ${packages[@]}; do
		find_rootfile "${path}" "${package}"
	done
}

find_rootfiles() {
	local path="${1}"
	shift

	# Descend into directories
	if [ -d "${path}" ]; then
		descend "${path}" "$@"

	# Or look straight for a file
	else
		find_rootfile "${path}" "$@"
	fi
}

# This function takes a list of rootfiles from standard input and extracts all files
read_rootfiles() {
	xargs -n 64 grep --no-filename -v "^#" | sort -u
}

substitute_paths() {
	sed \
		-e "s/BUILDTARGET/${BUILDTARGET}/g" \
		-e "s/KVER/${KVER}/g" \
		-e "s/xxxMACHINExxx/${BUILD_ARCH}/g"
}

main() {
	local arch="${1}"
	shift

	# Find all rootfiles
	find_rootfiles "$@" | read_rootfiles | substitute_paths
}

main "$@" || exit $?
