#!/bin/bash

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

function integrationEnabled {
	[ "$DISABLE_INTEGRATION" != "true" ]
}

function fileExistsInDir {
	local DIR="$1"
	local FILE="$2"
	# File tests and prefix test
	[ -d "$DIR" ] &&
		[ -e "$FILE" ] &&
		(( ${#DIR} < ${#FILE} )) &&
		[ "${FILE:0:${#DIR}}" == "$DIR" ]
}

function updatePathLink {
	local CONFIGDIR="$1" LINKDIR="$2" RELATIVE_PATH="$3"
	local LINK="$LINKDIR/$RELATIVE_PATH"
	local LINKEDFILE="$(realpath -e "$LINK" 2> /dev/null)"
	if [ -L "$LINK" ] && ( ! integrationEnabled || ! fileExistsInDir "$CONFIGDIR" "$LINKEDFILE" )
	then
		! integrationEnabled ||
			traceLog "Removing link $LINK: Referenced file doesn't exist in configured dir"
		rm -v "$LINK"
	fi
	if [ ! -L "$LINK" ] && integrationEnabled && [ -d "$CONFIGDIR" ] && [ -e "$CONFIGDIR/$RELATIVE_PATH" ]
	then
		traceLog "Creating link $LINK: File exists in configured dir"
		ln -sv "$CONFIGDIR/$RELATIVE_PATH" "$LINK"
	fi
}

function updateWrapperLink {
	local BINARYNAME="$1"
	local LINK="/usr/bin/$BINARYNAME"
	local WRAPPEDBINARY="$QEMU_BIN_DIR/$BINARYNAME"
	if [ -L "$LINK" ] && ( ! integrationEnabled || ! fileExistsInDir "$QEMU_BIN_DIR" "$WRAPPEDBINARY" )
	then
		! integrationEnabled ||
			traceLog "Removing wrapper link $LINK: Wrapped binary doesn't exist in configured dir"
		rm -v "$LINK"
	fi
	if [ ! -L "$LINK" ] && integrationEnabled && [ -f "$WRAPPEDBINARY" ]
	then
		traceLog "Creating wrapper link $LINK: Binary exists in configured dir"
		ln -sv "/usr/share/qemu-integration/qemu-wrapper.sh" "$LINK"
	fi
}

function determineManPaths {
	if [ -d "$QEMU_MAN_BASE_DIR" ]
	then
		cd "$QEMU_MAN_BASE_DIR"
		find man* -name "qemu*" 2> /dev/null
	fi
	cd "/usr/share/man"
	find man* -name "qemu*" 2> /dev/null
}

function determineQemuFiles {
	if [ -d "$QEMU_BIN_DIR" ]
	then
		cd "$QEMU_BIN_DIR"
		find -maxdepth 1 -name "qemu-*.exe" ! -name "qemu-*w.exe" ! -name "qemu-uninstall.exe"
		find -maxdepth 1 -name "elf2dmp.exe"
	fi
	cd "/usr/bin"
	find -maxdepth 1 -name "qemu-*.exe" ! -name "qemu-*w.exe" ! -name "qemu-uninstall.exe"
	find -maxdepth 1 -name "elf2dmp.exe"
}

determineConfig

# Complain about missing config
if integrationEnabled && [ ! -d "$QEMU_BIN_DIR" ]
then
	infoLog
	if [ -n "$QEMU_BIN_DIR" ]
	then
		infoLog "Current configured QEMU_BIN_DIR $QEMU_BIN_DIR doesn't exist."
	fi
	infoLog "Please adjust /etc/qemu-integration.conf for a working qemu integration"
	infoLog
fi

# Update wrapper symlinks
for QFILE in $( determineQemuFiles | sort | uniq )
do
	updateWrapperLink "$QFILE"
done

# Update man symlinks
for MPATH in $( determineManPaths | sort | uniq )
do
	updatePathLink "$QEMU_MAN_BASE_DIR" "/usr/share/man" "$MPATH"
done

# Update firmware symlinks
mkdir -p "/usr/share/qemu"
updatePathLink "$(dirname "$QEMU_FIRMWARE_DIR")" "/usr/share/qemu" "firmware"
rmdir --ignore-fail-on-non-empty "/usr/share/qemu"
