# Library for resolving and validating Java runtime for limine-entry-tool

JAVA_MIN_VERSION=17
JAVA_CMD=""

log_error() {
	local msg="$1"
	printf '\033[1;31m Error: %s\033[0m\n' "$msg" >&2
	[[ -n "$SCRIPT_NAME" ]] && logger -t "$SCRIPT_NAME" -p err "$msg"
}

# Parse a configuration file and export JAVA_BIN_PATH if defined.
export_java_bin_path() {
	local config_file="$1" key value
	while IFS='=' read -r key value; do
		[[ $key == "JAVA_BIN_PATH" ]] || continue
		# Trim surrounding whitespace and optional quotes
		value="${value//\"/}"
		value="${value#"${value%%[![:space:]]*}"}"
		value="${value%"${value##*[![:space:]]}"}"
		export JAVA_BIN_PATH="$value"
		return 0
	done <"$config_file"
}

# Load configuration from multiple possible locations
load_config() {
	local config_files=(
		/usr/share/limine-entry-tool.d/*.conf
		/etc/limine-entry-tool.conf
		/etc/limine-entry-tool.d/*.conf
		/etc/default/limine
	)
	for file in "${config_files[@]}"; do
		[[ -f "$file" ]] || continue
		export_java_bin_path "$file"
	done
}

# Resolve the Java command to be used.
# Prefer JAVA_BIN_PATH, otherwise fallback to system java.
resolve_java_cmd() {
	# Clear conflicting environment variables in the root environment.
	unset JAVA_HOME JAVA_OPTS JDK_JAVA_OPTIONS JAVA_TOOL_OPTIONS

	if [[ -n "$JAVA_BIN_PATH" && -x "$JAVA_BIN_PATH/java" ]]; then
		JAVA_CMD="$JAVA_BIN_PATH/java"
	elif command -v java &>/dev/null; then
		JAVA_CMD="java"
	else
		log_error "Java is not installed or not found in PATH."
		return 1
	fi
}

# Check whether the resolved Java version meets the minimum requirement.
check_java_version() {
	local version_str version_major
	version_str=$("$JAVA_CMD" -version 2>&1 | awk -F '"' '/version/ {print $2}')

	# Extract major version
	version_major="${version_str%%.*}"
	if ((version_major < JAVA_MIN_VERSION)); then
		log_error "Detected Java version ${version_str} is below the required minimum ${JAVA_MIN_VERSION}"
		return 1
	fi
}

# Public function: returns resolved Java command if valid
get_java_command() {
	load_config
	resolve_java_cmd || return 1
	check_java_version || return 1
	echo "$JAVA_CMD"
}
