#!/usr/bin/env bash

### Path to lock file
readonly SCRIPT_NAME="limine-snapper-sync"
readonly RESTORE_LOCKFILE="/tmp/limine-snapper-restore.lock"
readonly LIMINE_LOCK_FILE="/tmp/limine-global.lock"

_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
}

### Check if the script is being run with root privileges
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=30 200 || {
		warning_msg "Mutex lock timeout on ${name}."
		return 1
	}
}

mutex_unlock() {
	flock --unlock 200
}

# Main logic
if [ -e "${RESTORE_LOCKFILE}" ]; then
	warning_msg "limine-snapper-restore is already running."
	exit 1
fi

# Run the Java application
mutex_lock "${SCRIPT_NAME}"
/usr/lib/limine/limine-snapper-sync --update "$@"
exit_code="$?"
mutex_unlock

exit "$exit_code"
