#! /bin/sh

set -e

# Exit with a usage message if no arguments are specified.

if [ $# -eq 0 ]
then
    echo "Usage: $0 <url>" >&2
    exit 1
fi

URL="$1"    # The URL to open.

# Check if the URL to open is a valid URL.  It should start with the HTTP
# protocol prefix.  Give a diagnostic message nad exit if this is not the case.

PROTO_PRE="http://"

case "$URL" in

    $PROTO_PRE* )    # Correct protocol prefix: do nothing.

        ;;

    * )    # Incorrect prefix: print a daignostic message and exit.

        echo "$0: URL does not start with protocol prefix, $PROTO_PRE: $URL" \
             >&2
        exit 1
        ;;

esac

# Set the order of commands to check dependent from the session environment.

if [ -n "$GNOME_DESKTOP_SESSION_ID" ]
then
    # We have a Gnome desktop running. Try gnome-open first.
    COMMANDS="gnome-open exo-open kde-open xdg-open"
elif [ -n "$KDE_FULL_SESSION" ]
then
    # We have a KDE desktop running. Try kde-open first.
    COMMANDS="kde-open exo-open gnome-open xdg-open"
else
    # Try Xfce's exo-open command first.
    COMMANDS="exo-open kde-open gnome-open xdg-open"
fi

# Execute the first existing command to open the URL.

for CMD in $COMMANDS
do
   if which $CMD >/dev/null 2>&1
   then
       exec $CMD "$URL"
   fi
done

# Print a diagnostic message if no command to open the URL could be found.

echo "$0: Could not find command to open: $URL" >&2

exit 1
