#!/bin/bash
export GDK_BACKEND="wayland"
export XDG_SESSION_TYPE="wayland"

cat >/tmp/.mbweston.ini << EOF
[shell]
background-color=0xff000000
panel-location=""
[core]
repaint-window=15
EOF

WAYSOCKNAME="WebKitTestSocket${RANDOM}"
WAYSOCKETFILE="/run/user/${UID}/${WAYSOCKNAME}"

function teardown() {
    for cpid in $(pgrep -P $$); do kill -TERM "${cpid}" &>/dev/null; done
    sleep 0.25
    for cpid in $(pgrep -P $$); do kill -QUIT "${cpid}" &>/dev/null; done
    sleep 0.25
    for cpid in $(pgrep -P $$); do kill -KILL "${cpid}" &>/dev/null; done
    rm -f "${WAYSOCKETFILE}"
    exit 0
}

function runweston() {
    if test -e "${WAYSOCKETFILE}" && grep -q "${WAYSOCKETFILE}" /proc/net/unix; then
        echo "Weston socket /run/user/${UID}/WebKitTestSocket in use. Not starting weston"
        # Disable trap
        trap "" INT TERM QUIT EXIT
    else
        echo "Starting weston with resolution ${1}x${2}"
        weston --width=${1} --height=${2} --idle-time=0 --config=/tmp/.mbweston.ini -B x11-backend.so --socket="${WAYSOCKNAME}" &>/dev/null &
        sleep 0.5;
    fi
}

trap "teardown" INT TERM QUIT EXIT


runweston 1280 720
export WAYLAND_DISPLAY="${WAYSOCKNAME}"
unset DISPLAY
if test -x "$1" || test -x "$(which ${1} 2>/dev/null)"; then
    echo "Running: $@"
    $@
else
    echo "Running: Tools/Scripts/run-minibrowser --wpe $@"
    Tools/Scripts/run-minibrowser --wpe $@
fi
