#!/usr/bin/sh

. /etc/blackPanther-default-apps.conf

echo -en "${YEL}Caprine starting on $(lsb_release -sir)....$DEF"
if [ -n "$(env | grep -v grep | grep -i 'DBUS_SESSION_BUS_ADDRESS=unix')" ];then
    DBUS=yes
fi
LIB=/usr/lib
[ "$(uname -m)" = "x86_64" ] && LIB=/usr/lib64
if [ -x $LIB/$(basename $0)/caprine ];then
RUNPATH="$LIB/$(basename $0)/caprine"
elif [ -x $LIB/caprine/caprine ];then 
RUNPATH=$LIB/caprine/caprine
elif [ -x $LIB/caprine-ce/caprine ];then
RUNPATH=$LIB/caprine-ce/caprine
elif [ -x $LIB/caprine/caprine-ce ];then 
RUNPATH=$LIB/caprine/caprine-ce
elif [ -x $LIB/caprine-ce/caprine-ce ];then
RUNPATH=$LIB/caprine-ce/caprine-ce
else
echo "Missing binary on path..Please report me on http://bugs.blackpanther.hu"
exit 1
fi
run() { 

if [ "$DBUS" = "yes" ];then
echo " [normal]"
$RUNPATH
else
echo " [dbusfix]"
dbus-launch $RUNPATH
fi
exit 0
}


if [ -n "$DISPLAY" ] && [ "$DBUS" != "yes" ];then
    machine_id=$(LANGUAGE=C hostnamectl|grep 'Machine ID:'| sed 's/^.*: //')
    x_display=`echo $DISPLAY|sed 's/^.*:\([0-9]\+\)\(\.[0-9]\+\)*$/\1/'`
    dbus_session_file="$HOME/.dbus/session-bus/${machine_id}-${x_display}"
    #echo $dbus_session_file
    if [ -r "$dbus_session_file" ]; then
            export $(grep '^DBUS.*=' "$dbus_session_file")
            # check if PID still running, if not launch dbus
            ps $DBUS_SESSION_BUS_PID | tail -1 | grep dbus-daemon >& /dev/null
            [ "$?" != "0" ] && export $(dbus-launch) >& /dev/null
            DBUS=yes
            run
    else
            export $(dbus-launch) >& /dev/null
            run
    fi

fi
run


