#!/bin/bash

WRAPPER="qemu-wrapper.sh"

source /usr/share/qemu-integration/functions.sh

function dirname {
	if [[ $1 =~ ^(.+)/[^/]+ ]]
	then
		echo "${BASH_REMATCH[1]}"
	elif [[ $1 =~ ^/[^/]+$ ]]
	then
		echo "/"
	elif [[ $1 =~ ^[^/]+$ ]]
	then
		echo "."
	fi
}

function commonPathPrefix {
	if [ "$1" != "$2" ]
	then
		if (( ${#1} < ${#2} ))
		then
			commonPathPrefix "$1" "$(dirname "$2")"
		else
			commonPathPrefix "$2" "$(dirname "$1")"
		fi
	else
		echo "$1"
	fi
}

function qcygpath {
	cygpath -m -l "$1"
}

function qrealpath {
	local FILE=$(realpath "$1")
	if (( ${#FILE} >= ${#CYGUROOT} )) &&
		[ "${FILE:0:${#CYGUROOT}}" == "${CYGUROOT}" ]
	then
		echo "${FILE:${#CYGUROOT}}"
	else
		echo "$FILE"
	fi
}

function translateExistingPath {
	local PARAM=$1
	debugLog "Existing path to translate: $PARAM"
	if [[ $PARAM =~ ^/ ]]
	then
		traceLog "Absolute path"
		if [[ ! $PARAM =~ ^/(dev|proc)(/|$) ]]
		then
			debugLog "Regular path, use cygpath"
			qcygpath "$PARAM"
		else
			debugLog "Won't translate special absolute path"
			echo "$PARAM"
		fi
	else
		traceLog "Relative path"
		local PARAMPATH="$(qrealpath "$PARAM")"
		local WORKINGDIR="$(qrealpath .)"
		local COMMONDIR="$(commonPathPrefix "$WORKINGDIR" "$PARAMPATH")"
		debugLog "Paths by realpath: commondir:$COMMONDIR - workingdir:$WORKINGDIR - path:$PARAMPATH"
		if [ "$COMMONDIR" == "/" ] && [[ $PARAMPATH =~ ^/cygdrive ]]
		then
			debugLog "Path is outside of relative sight, use cygpath"
			qcygpath "$PARAM"
		else
			debugLog "Path is file/dir in working dir or in super of working dir, turn relative"
			local PREFIX="."
			while [ "$WORKINGDIR" != "$COMMONDIR" ]
			do
				WORKINGDIR="$(dirname $WORKINGDIR)"
				PREFIX="../$PREFIX"
			done
			echo "$( echo "$PREFIX" | sed "s%/\.$%%" )${PARAMPATH:${#COMMONDIR}}" | sed "s%^\./%%"
		fi
	fi
}

function translatePotentialPath {
	local PARAM="$1"
	traceLog "Potential path to translate: $PARAM"
	if [[ $PARAM =~ ^.: ]] || [[ $PARAM =~ \\ ]]
	then
		traceLog "Looks like Windows path, no translation"
		echo "$PARAM"
	elif [ -e "$PARAM" ]
	then
		debugLog "Is existing file/dir, go on..."
		translateExistingPath "$PARAM"
		debugLog
	elif [ ! -L "$PARAM" ] && [[ $PARAM =~ /.+ ]]
	then
		traceLog "Is no dangling link and contains a slash..."
		local DPARAM=$(dirname "$PARAM")
		local BPARAM=$(basename "$PARAM")
		if [ -d "$DPARAM" ]
		then
			debugLog "Path has existing super dir $DPARAM, go on ..."
			local ODPARAM="$DPARAM"
			DPARAM=$(translateExistingPath "$DPARAM")
			if [ "$ODPARAM" != "$DPARAM" ]
			then
				traceLog "Translated to $DPARAM/$BPARAM"
				echo "$DPARAM/$BPARAM"
			else
				traceLog "Not modified on translation"
				echo "$PARAM"
			fi
			debugLog
		else
			traceLog "No translation"
			echo "$PARAM"
		fi
	else
		traceLog "No translation"
		echo "$PARAM"
	fi
}

function translateParam {
	local PARAM="$1"
	traceLog "Analyse param for translation: $PARAM"
	if [[ $PARAM =~ = ]]
	then
		traceLog "Param contains '=', assuming comma-separated key-value list"
		local REST="$PARAM" TRANS=""
		while [[ $REST =~ ^([^,]+),?(.*) ]]
		do
			local TOKEN="${BASH_REMATCH[1]}" REST="${BASH_REMATCH[2]}"
			if [[ $TOKEN =~ ^(logfile|file|filename|path|splash|script|x509-[^=]+)=(.+)$ ]]
			then
				traceLog "Token: '$TOKEN'"
				local TOKEN_NAME="${BASH_REMATCH[1]}" TOKEN_OVALUE="${BASH_REMATCH[2]}"
				local TOKEN_TVALUE="$(translatePotentialPath "$TOKEN_OVALUE")"
				TOKEN="${TOKEN_NAME}=${TOKEN_TVALUE}"
			fi
			TRANS="${TRANS}${TOKEN},"
		done
		echo "${TRANS::-1}"
	else
		traceLog "Assuming plain param"
		translatePotentialPath "$PARAM"
	fi
	traceLog
}

# Try to determine and translate unix to windows paths 
declare -a QPARAMS=()
CYGWROOT=$( qcygpath / )
CYGUROOT=$( echo "$CYGWROOT" | sed "s%^\(.\):%/cygdrive/\L\1%" )
TAPPLIED="false"
for QPARAM in "$@"
do
	if [ -z "$DISABLE_PATH_TRANSLATION" ]
	then
		TPARAM=$(translateParam "$QPARAM")
		if [ "$TPARAM" != "$QPARAM" ]
		then
			TAPPLIED="true"
		fi
		QPARAM="$TPARAM"
	fi
	QPARAMS+=("$QPARAM")
done
if [ -z "$DISABLE_PATH_TRANSLATION" ] && $TAPPLIED
then
	infoLog
	infoLog "/usr/share/qemu-integration/$WRAPPER applied its path translation:"
	infoLog "$(basename $0) ${QPARAMS[@]}"
	infoLog
fi

# Define native windows title bar if not defined otherwise
if [ -z "$GTK_CSD"]
then
	export GTK_CSD=0
fi

determineConfig

# Add mingw/bin and configured extension to PATH
export PATH="$QEMU_BIN_DIR:$WRAPPER_ENV_PATH_EXTENSION:$PATH"

# Determine binary to execute
QBINARY="$QEMU_BIN_DIR/$(basename $0)"
debugLog "$QBINARY"
if [ ! -f "$QBINARY" ]
then
	# Suffix .exe was not used on invocation
	QBINARY="$QBINARY.exe"
	debugLog "$QBINARY"
fi
exec "$QBINARY" "${QPARAMS[@]}"
