# -*- mode: shell-script; -*-

start on started dbus_system

pre-start script
    # deal with dbus not being present
    [ -x /usr/bin/dbus-daemon ] || stop
    mkdir -p /var/run/dbus /var/lib/dbus

    if [ ! -f /var/lib/dbus/machine-id ]; then
        echo 8564ef71cceddcecee092de2386d4386 > /var/lib/dbus/machine-id
    fi
end script

script
    # Need to use || here since the script is run with -e
    /usr/bin/dbus-daemon --nofork --session || \
        /usr/sbin/reboot_dbus_if.sh $? $UPSTART_JOB
end script

post-start script
    # Wait here until the bus is ready.  Folks waiting on me to
    # "start" won't get that event until this script finishes
    TIMEOUT_SECS=15
    THEN=$((TIMEOUT_SECS + $(date "+%s"))) # timeout in case dbus never comes up

    while :; do
        # look for ports 4444 and 4445 opened; means the busses are listening
        grep -q '00000000:115C' /proc/net/tcp \
            && grep -q '00000000:115D' /proc/net/tcp \
            && break
        usleep 10000

        # If it takes more than five seconds for dbus to init its
        # sockets something is fatally wrong
        if [ $(date "+%s") -gt $THEN ]; then
            logger -s "$UPSTART_JOB: $TIMEOUT_SECS seconds passed without dbus socket[s] appearing; rebooting."
            reboot
            # Don't keep looping or logs fill up. Even 'exit 1' sends
            # an event to the next jobfile
            sleep 60
        fi
    done
end script
