#!/bin/sh

set -eu

. /usr/share/geordi/_functions
. ${CONFIG_DIR}/compile-config

info "Running 'trycompile'"

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


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
		error "Maximum number of trycompile iterations tried"
	fi

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

	# grep the error from GCC.
	if echo "$GCC_ERROR" | grep "No such file" > /dev/null;
	then
		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 "ld: cannot find -l" > /dev/null;
	then
		debug "Missing an '.a' file"

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

		if FULL_PATH="$(find_file lib${FILE}.a)";
		then
			copy_file "${FULL_PATH}"
		elif FULL_PATH="$(find_file lib${FILE}.so)";
		then
			copy_file "${FULL_PATH}"
		else
			error "Could not find -l${FILE} variant"
			exit 1
		fi

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