#!/bin/sh

set -eu

mkdir -p /run/dbus
dbus-daemon --system --nofork&
dbus_pid=$!

echo "Launching dbus-daemon"

echo "Launching logid"
logid -v --config logid.example.cfg 2>&1 &

logid_pid=$!
echo "logid pid=$logid_pid"

# ensure still alive after 10 seconds
echo "Waiting for 10 seconds"
sleep 10

echo "Killing logid with SIGTERM"
kill -TERM "$logid_pid" || {
    echo "Could not find logid process. It probably crashed"
    exit 1
}

echo "Waiting for logid to terminate"
# ensure that SIGTERM kills the process
shpid=$$
(sleep 10 && echo Timeout &&  kill -9 $shpid || exit 0) &
timeout_pid=$!

wait "$logid_pid" || true
echo "logid terminated, cleaning up"

kill "$timeout_pid" "$dbus_pid" || true
