#!/bin/sh

set -eu

. /usr/share/geordi/_functions

Echo_info "Copying libraries"

Echo_debug "Writing test .cpp file"
printf "#include \"prelude.hpp\"\nGEORDI_PRINT_PRE 9 GEORDI_PRINT_POST\n" > "${RT}/t.cpp"

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

	Echo_debug "Looking for ${FILE}"

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

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

	return 1
}

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

	if [ -z "${FILE}" ]
	then
		Echo_error "Refusing to copy invalid filename"
		exit 1
	fi

	Echo_debug "Installing file ${FILE}"

	if FULL_PATH=$(Find_file "${FILE}")
	then
		Copy_file "${FULL_PATH}"
	else
		Echo_error "Could not find ${FILE}"
		exit 1
	fi
}

while ! GCC_ERROR="$(chroot ${RT} ${GXX} ${COMPILE_FLAGS} ${LINK_FLAGS} t.cpp prelude.a -o t 2>&1)"
do
	TRYCOMPILE_MAX=$((${TRYCOMPILE_MAX} - 1))

	if [ ${TRYCOMPILE_MAX} -le 0 ];
	then
		Echo_error "Maximum number of trycompile iterations tried"
		exit 1
	fi

	Echo_debug "Running 'trycompile' again (${TRYCOMPILE_MAX} attempts left)"

	# grep the error from GCC.
	if echo "$GCC_ERROR" | grep -qs "No such file"
	then
		Echo_debug "Missing a .so file"

		FILE=$(echo "${GCC_ERROR}" | sed -n 's/.*ld: \(.*\): No such file:.*/\1/gp')
		Install_file "${FILE}"

	elif echo "$GCC_ERROR" | grep -qs "^ld: cannot find /"
	then
		Echo_debug "Missing a particular file"

		FILE=$(echo "${GCC_ERROR}" | sed -n 's/^ld: cannot find \(.*\)/\1/gp')
		Install_file "${FILE}"

	elif echo "${GCC_ERROR}" | grep -qs "ld: cannot find -l"
	then
		Echo_debug "Missing an '-lFOO' file"

		FILE=$(echo "${GCC_ERROR}" | sed -n 's/.*ld: cannot find -l\(.*\)/\1/gp')

		if FULL_PATH="$(Find_file lib${FILE}.so)"
		then
			Copy_file "${FULL_PATH}"
		elif FULL_PATH="$(Find_file lib${FILE}.a)"
		then
			Copy_file "${FULL_PATH}"
		else
			Echo_error "Could not find -l${FILE} variant"
			exit 1
		fi

	else
		Echo_error "Could not interpret GCC error: ${GCC_ERROR}"
		exit 1
	fi
done
