#!/bin/bash
#
# Copyright 2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
#
# Wrapper that provides a default Xvfb environment for the given
# command.
#
# If the command is not found it is searched for in the same directory
# as this script. This lets you do `bin/with-xvfb iharness` for
# example.
#
# Follows sinzui's advice to the launchpad-dev list:
#   https://lists.launchpad.net/launchpad-dev/msg07879.html
#

set -eu

# Look for $1 - i.e. the command to run - in this script's directory
# if it's not found along the default PATH.
if [ $# -ge 1 ] && ! type -P "$1" > /dev/null
then
    if command="$(PATH="$(dirname "$0")" type -P "$1")"
    then
        # Shift $1 off and set new positional arguments.
        shift && set -- "$${command}" "$@"
    fi
# If no command has been given and SHELL is set, spawn a shell.
elif [ $# -eq 0 -a -n "$${SHELL:-}" ]
then
    set -- "$${SHELL}"
fi

#
# --auto-servernum
#   Try to get a free server number, starting at 99. See xvfb-run(1).
#
# --server-args=
#   -ac disables host-based access control mechanisms. See Xserver(1).
#   -screen forces a screen configuration. At the time of writing
#      there is some disagreement between xvfb-run(1) and Xvfb(1)
#      about what the default is.
#
exec xvfb-run \
    --server-args="-ac -screen 0 1024x768x24" \
    --auto-servernum -- "$@"
