#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 1 ]]; then
	echo "Usage: gledit <filename>" >&2
	exit 2
fi

# Resolve the real script location so a PATH symlink in ~/.local/bin still
# finds the repository build while developing, as well as the adjacent binary
# in an installed package.
script_path="$(readlink -f -- "${BASH_SOURCE[0]}")"
script_dir="$(CDPATH= cd -- "$(dirname -- "$script_path")" && pwd -P)"
desktop="${GLDOZE_DESKTOP:-}"
if [[ -z "$desktop" ]]; then
	for candidate in \
		"$script_dir/gldoze_desktop" \
		"$script_dir/../build-cef-codecs/gldoze_desktop" \
		"$script_dir/../build-cef/gldoze_desktop" \
		"$script_dir/../build/gldoze_desktop"; do
		if [[ -x "$candidate" ]]; then
			desktop="$candidate"
			break
		fi
	done
fi
if [[ -z "$desktop" ]]; then
	desktop="$(command -v gldoze_desktop 2>/dev/null || true)"
fi
if [[ -z "$desktop" || ! -x "$desktop" ]]; then
	echo "gledit: gldoze_desktop was not found beside this command or on PATH" >&2
	exit 127
fi

# The desktop owns the editor window. Resolve relative paths here because the
# running desktop may have been started from a different working directory.
file_path="$(readlink -f -- "$1" 2>/dev/null || true)"
if [[ -z "$file_path" ]]; then
	if [[ "$1" = /* ]]; then
		file_path="$1"
	else
		file_path="$PWD/$1"
	fi
fi

# This is a short-lived client request. It must never create a second desktop
# process just to open one GLEdit document.
exec "$desktop" --open-existing --open-app gledit --open-file "$file_path"
