#!/usr/bin/env bash

readonly SCRIPT_NAME="limine-entry-tool"
readonly LIMINE_LOCK_FILE="/tmp/limine-global.lock"
ENABLE_MUTEX="yes"
ARGS=()

for arg in "$@"; do
	if [[ "$arg" == "--no-mutex" ]]; then
		ENABLE_MUTEX="no"
	else
		ARGS+=("$arg")
	fi
done

_color_reset=""
_color_yellow=""
_color_red=""
colors="$(tput colors 2>/dev/null || echo 0)"
if ((colors >= 8)); then
	_color_reset="\033[0m"
	_color_yellow="\033[1;33m"
	_color_red="\033[1;31m"
fi

warning_msg() {
	echo -e "${_color_yellow}WARNING: $1${_color_reset} ${2:-}" >&2
}

error_msg() {
	echo -e "${_color_red}ERROR: $1${_color_reset} ${2:-}" >&2
}

if [[ $EUID -ne 0 ]]; then
	error_msg "${SCRIPT_NAME} must be run with root privileges."
	exit 1
fi

mutex_lock() {
	local name=$1
	exec 200>${LIMINE_LOCK_FILE} || {
		rm -f ${LIMINE_LOCK_FILE}
		exec 200>${LIMINE_LOCK_FILE}
	}
	flock --timeout=10 200 || {
		warning_msg "Mutex lock timeout on ${name}."
		return 1
	}
}

mutex_unlock() {
	flock --unlock 200
}

if [[ "${ENABLE_MUTEX}" == "yes" ]]; then
	mutex_lock "${SCRIPT_NAME}"
fi

/usr/lib/limine/limine-entry-tool "${ARGS[@]}"
exit_code="$?"

if [[ "${ENABLE_MUTEX}" == "yes" ]]; then
	mutex_unlock
fi

exit "$exit_code"
