#!/bin/sh

# Run spectrwm under Xvfb and detect its presence using wmctrl

wait_command()
{
    local command="$1"
    local expected_rc="$2"

    local tries=15

    while true
    do
        sh -c "$command" 2>&1
        test "$?" -eq "$expected_rc" && {
            return 0
        }

        tries=$(expr "$tries" - 1)
        test "$tries" -le 0 && {
            return 1
        }

        sleep 1
    done
}

# Make sure the test environment is sane. Neither Xvbf nor
# spectrwm should be already running, or we would risk killing
# unrelated processes in the teardown phase

echo '# Validating test environment...'
wait_command 'pgrep Xvfb' 1 || exit 1
wait_command 'pgrep spectrwm' 1 || exit 1

# Setup

export DISPLAY=:3

echo '# Starting Xvfb...'
Xvfb $DISPLAY >Xvfb.log 2>&1 &
wait_command 'pgrep Xvfb' 0

echo '# Waiting for Xvfb...'
wait_command "xdpyinfo" 0

echo '# Starting spectrwm...'
spectrwm >spectrwm.log 2>&1 &
wait_command 'pgrep spectrwm' 0

# Test

echo '# Detecting spectrwm...'
wait_command 'wmctrl -m | grep spectrwm' 0
rc=$?

# Teardown

echo '# Stopping spectrwm...'
pkill spectrwm
wait_command 'pgrep spectrwm' 1

echo '# Stopping Xvfb...'
pkill Xvfb
wait_command 'pgrep Xvfb' 1

test "$rc" -eq 0 || {
    cat Xvfb.log spectrwm.log >&2
}

exit $rc
