#!/bin/sh

# This is the list of supported window manager binaries
WMS=("metacity" "kwin_x11" "kwin" "xfwm4" "openbox" "marco")

run_metacity()
{
    # Apply the anaconda overrides before running metacity
    if [ -z "$XDG_DATA_DIRS" ] ; then
        new_data_dirs="/usr/share/anaconda/window-manager:/usr/share"
    else
        new_data_dirs="/usr/share/anaconda/window-manager:${XDG_DATA_DIRS}"
    fi
    XDG_DATA_DIRS="$new_data_dirs" $1 &
}

# Get the application binary to start and remove it from
# the argument list
BINARY=$1
shift

for WM in ${WMS[@]}; do
    FILE=$(which $WM 2>/dev/null)
    FOUND=$?

    if [ $FOUND -eq 0 -a -x "$FILE" ]; then
        # start window manager
        if [ "$WM" == "metacity" ]; then
            # if running Metacity apply the Anaconda/Initial Setup custom overrides
            printf "MESSAGE=Running Metacity with custom overrides\nPRIORITY=6" | logger --journald
            run_metacity "$FILE"
        else
            printf "MESSAGE=Running window manager ($FILE)\nPRIORITY=6" | logger --journald
            "$FILE" &
        fi

        pid=$!

        # start the application
        printf "MESSAGE=Running ($BINARY)\nPRIORITY=6" | logger --journald
        $BINARY "$@"
        res=$?

        # stop window manager
        printf "MESSAGE=Stopping the window manager ($FILE)\nPRIORITY=6" | logger --journald
        ps -p $pid >/dev/null && kill $pid

        # return result
        exit $res
    fi
done

# No known window manager found
printf "MESSAGE=No supported window manager found!\nPRIORITY=3" | logger --journald
exit 1
