#!/bin/bash

function infoLog {
	>&2 echo "$@"
}

function traceLog {
	[ -z "$WRAPPER" ] && local SCRIPT="$0" || local SCRIPT="$WRAPPER"
	[ -n "$QTRACE" ] && infoLog "TRACE $SCRIPT:${FUNCNAME[1]}: $@"
}

function debugLog {
	[ -z "$WRAPPER" ] && local SCRIPT="$0" || local SCRIPT="$WRAPPER"
	([ -n "$QDEBUG" ] || [ -n "$QTRACE" ]) && infoLog "DEBUG $SCRIPT:${FUNCNAME[1]}: $@"
}

function sysrootQemuTest {
	local TEST="$1"
	traceLog "$TEST"
	local MINGWROOT="/usr/$TEST/sys-root/mingw"
	if [ -f "$MINGWROOT/share/qemu/bios.bin" ]
	then
		debugLog "qemu is installed in $MINGWROOT, using default configuration"
		QEMU_BIN_DIR="$MINGWROOT/bin"
		QEMU_MAN_BASE_DIR="$MINGWROOT/share/man"
		QEMU_FIRMWARE_DIR="$MINGWROOT/share/qemu/firmware"
	fi
}

function programFilesQemuTest {
	local TEST="$1"
	traceLog "$TEST"
	local QDIR="/cygdrive/c/$TEST/qemu"
	if [ -d "$QDIR" ]
	then
		traceLog "Examing $QDIR"
		local QUI="$(find "$QDIR" -type "f" -name "qemu-uninstall.exe")"
		if [ -f "$QUI" ]
		then
			debugLog "qemu is installed in $QDIR, using default configuration"
			QEMU_BIN_DIR="$(dirname "$QUI")"
		fi
	fi
}

function determineConfig {
	[ -f "/etc/qemu-integration.conf" ] && source "/etc/qemu-integration.conf"
	if [ -z "$QEMU_BIN_DIR" ]
	then
		debugLog "QEMU_BIN_DIR isn't configured"
		declare -a TESTS=()
		[ "$(uname -m)" == "x86_64" ] &&
			TESTS=("x86_64-w64-mingw32" "Program Files" "i686-w64-mingw32" "Program Files (x86)") ||
			TESTS=("i686-w64-mingw32" "Program Files (x86)" "x86_64-w64-mingw32" "Program Files")
		for TEST in "${TESTS[@]}"
		do
			traceLog "$TEST"
			if [ -z "$QEMU_BIN_DIR" ]
			then
				[[ $TEST =~ mingw32$ ]] &&
					sysrootQemuTest "$TEST" ||
					programFilesQemuTest "$TEST"
			fi
		done
		debugLog "QEMU_BIN_DIR is '$QEMU_BIN_DIR'"
	fi
}

function qexec {
	if [ -n "$QEXEC_DUMP" ]
	then
		if ! touch "$QEXEC_DUMP" || ! truncate -s 0 "$QEXEC_DUMP"
		then
			infoLog "Can't use dump file: QEXEC_DUMP='$QEXEC_DUMP'"
			exit 1
		fi
		local I=1 L=$#
		while (( I <= L ))
		do
			printf "QEXEC%03d=%s\n" "$I" "${!I}" >> "$QEXEC_DUMP"
			I=$(( I+1 ))
		done
	else
		exec "$@"
	fi
}
