#!/bin/sh -

# These ports should really be ordered by ease-of-use.  Most likely
# advanced users with many ports installed will invoke their preferred
# one directly rather than depend on this script...

PORTS="doom odamex crispy-doom prboom-plus eternity gzdoom chocolate-doom"

# Just a single argument starting the command is allowed, -p, in order
# to explicitly set a port on the command line. -- is also supported
# so that -p can be instead sent directly to the port's argument list.

if [ $# -gt 0 ]; then
    if [ "$1" = "-p" ]; then
        PORT="$2"
        shift; shift
    elif [ "$1" = "--" ]; then
        shift
    fi
fi

case "$(basename "$0")" in
    freedm)
        IWAD=freedm.wad
        ;;
    freedoom1)
        IWAD=freedoom1.wad
        ;;
    freedoom2 | *)
        IWAD=freedoom2.wad
        ;;
esac

if [ -z "$PORT" ] && [ -h "$HOME"/.doomport ]; then
    if [ -f "$(readlink -f "$HOME"/.doomport)" ] \
        && [ -x "$(readlink -f "$HOME"/.doomport)" ]; then
        PORT="$(readlink -f "$HOME"/.doomport)"
    fi
fi

if [ "$PORT" ]; then
    exec "$PORT" -iwad "$IWAD" "$@"
fi

dirpath=$(eval echo "\${PATH}" 2>/dev/null | tr : ' ')

for port in $PORTS; do
    for dir in $dirpath; do
        for file in "$dir"/"$port"; do
            if [ -f "$file" ] && [ -x "$file" ]; then
                exec "$file" -iwad "$IWAD" "$@"
            fi
        done
    done
done

# If we've reached this far, no engine was successfully executed.
# print message to stderr and exit with a status of 1.

cat <<EOF >&2
$(basename "$0") could not locate nor launch a Doom engine.  Most
likely, you simply need to install one, check your distribution
package repositories for names such as "prboom" or "odamex" or seek
out one and install it manually.

If you believe you already have one, you may just need to modify your
PATH environment variable to include it, or set up the $HOME/.doomport
symbolic link to point directly to the engine of your choice.
EOF
exit 1
