set -eu

error() {
	echo "E: ${@}, exiting..." 1>&2
	exit 1
}

info() {
	case "$(echo ${INFO} | tr A-Z a-z)" in
		yes|true|on|y|1)
			echo "I: ${@}" 1>&2
			;;
	esac
}

debug() {
	case "$(echo ${DEBUG} | tr A-Z a-z)" in
		yes|true|on|y|1)
			echo "D: ${@}" 1>&2
			;;
	esac
}

_find_libs() {
	local BINARY
	BINARY="${1}"
	ldd "${BINARY}" | runhaskell /usr/share/geordi/parse-ldd-output.hs
}

copy_file() {
	local FILE
	FILE="${1}"

	debug "Copying ${FILE} to chroot"

	case "$(echo ${DEBUG} | tr A-Z a-z)" in
		yes|true|on|y|1)
			cp -L -r --parents -v -- "${FILE}" "${RT}"
			;;
		*)
			cp -L -r --parents -- "${FILE}" "${RT}"
			;;
	esac
	
}

copy_libs_for_binary() {
	local BINARY
	BINARY="${1}"

	debug "Copying libraries for ${BINARY}"

	for LIB in $(_find_libs "${BINARY}");
	do
		copy_file "${LIB}"
	done
}

install_file() {
	local FILE
	FILE="${1}"

	debug "Installing file ${FILE}"

	if FULL_PATH=$(find_file "${FILE}");
	then
		copy_file "${FULL_PATH}"
	else
		error "Could not find ${FILE}"
		exit 1
	fi
}

find_file()
{
	local FILE
	FILE="${1}"
	debug "Looking for ${FILE}"

	LOCATION=$($(gcc_binary) -print-file-name="${FILE}")

	case "${LOCATION}" in
		/*)
			echo "${LOCATION}"
			return 0
			;;
	esac

	# Non-fatal, as caller may be trying multiple files.
	return 1
}

gcc_binary() {
	BINARY=$(which $(. "${CONFIG_DIR}/compile-config"; echo ${GXX}))

	if [ -z "${BINARY}" ];
	then
		error "Could not determine G++ binary from ${CONFIG_DIR}/compile-config"
	fi

	echo "${BINARY}"
}

gcc_target() {
	local GCC_TARGET
	GCC_TARGET=$($(gcc_binary) -dumpmachine)

	if [ -z "${GCC_TARGET}" ];
	then
		error "Could not determine target architecture"
	fi

	echo "${GCC_TARGET}"
}

gcc_version() {
	local GCC_VERSION
	GCC_VERSION=$($(gcc_binary) -v 2>&1 | awk '/^gcc version/ {print $3}')

	if [ -z "${GCC_VERSION}" ];
	then
		error "Could not determine GCC version"
	fi

	echo "${GCC_VERSION}"
}

