#!/bin/sh
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# This file is part of Déjà Dup.
# For copyright information, see AUTHORS.
#
# Déjà Dup is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Déjà Dup is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Déjà Dup.  If not, see <http://www.gnu.org/licenses/>.

# This wraps a test script in a comfortable, fake environment, so it doesn't
# screw with the rest of the system.
#
# Tests run in bare server environments (like when building on a build farm)
# need a dbus session to be launched, otherwise the first import ldtp fails.
# But dbus needs an X running.  So we run Xvfb and dbus-launch here.
#
# But in tests themselves, we still run a separate nested dbus-launch
# environment because that's the easiest way to get a fresh dconf session.

# This dbus-launch is only for ldtp's benefit.  We still need a dbus-launch
# run inside base.py to handle the dconf session
if [ -z "$DISPLAY" ]; then
  xvfb-run -a dbus-launch --exit-with-session sh -c "/usr/lib/gnome-settings-daemon/gnome-settings-daemon >/dev/null 2>&1 & sleep 2 && $*"
else
  $*
fi
exit

XVFB_PID=
ORIG_DBUS_PID="$DBUS_SESSION_BUS_PID"

cleanup() {
  if [ -n "$XVFB_PID" ]; then
    kill -9 "$XVFB_PID"
  fi

  if [ "$ORIG_DBUS_PID" != "$DBUS_SESSION_BUS_PID" ]; then
    kill -9 "$DBUS_SESSION_BUS_PID"
  fi
}

trap cleanup EXIT

if [ -z "$DISPLAY" ]; then
  # Run a Xvfb session to allow running the test suite without a monitor
  Xvfb :5 >/dev/null 2>/dev/null &
  XVFB_PID="$!"
  sleep 1 # give Xvfb time to start up
  export DISPLAY=:5
fi

eval `dbus-launch --sh-syntax --exit-with-session`
export DBUS_SESSION_BUS_PID
export DBUS_SESSION_BUS_ADDRESS

$1
