`xdg-open`, or how Linux desktop fxck everything up

In case you don’t know, xdg-open is “default open applications” for (GNU\)Linux desktop. The xdg-open implementation by freedestop sucks, below is a much more better one.

#!/bin/sh

help_message(){
	echo "$(basename "$0") -- opens a file or URL in the user's preferred application." | fmt -w80 >&2
	echo "Usage $(basename "$0") { file | URL }" >&2
}
# This handles backslashes but not quote marks.
first_word()
{
    read -r first rest
    echo "$first"
}
get_dexcmd(){
	[ -z "$1" ] && echo "$BROWSER" && return
	cmd="$(grep -E "^Exec(\[[^]=]*])?=" "$1" | cut -d= -f 2- | first_word)"
	cmd="$(command -v "$cmd")"

	if [ ! -t 0 ]; then
		term_needed=$(grep -E "^Terminal(\[[^]=]*])?=" "$1" | cut -d= -f 2-)
		[ -n "$term_needed" ] && [ "$term_needed" = "true" ] && [ -n "$cmd" ] && cmd="$TERMINAL -e $cmd"
	fi
	[ -n "$cmd" ] && echo "$cmd" || echo "$BROWSER"
}

[ $# -eq 0 ] && help_message && exit 1

exec 2>/dev/null

DEX_PATH="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

fileurl="$*"

if [ -f "$fileurl" ]; then
	dextype="$(xdg-mime query filetype "$fileurl")"
else
	dextype="x-scheme-handler/${fileurl%%:*}"
fi

[ -n "$dextype" ] && DEX_FILE="$(xdg-mime query default "$dextype" )"
if [ -n "$DEX_FILE" ]; then
	IFS=":"
	for p in $DEX_PATH; do
		if [ -f "$p/applications/$DEX_FILE" ]; then
			unset IFS
			exec $(get_dexcmd "$p/applications/$DEX_FILE") "$fileurl"
		fi
	done
fi
exec $BROWSER "$@"