#!/usr/bin/sh

#*********************************************************************************************************
#*   __     __               __     ______                __   __                      _______ _______   *
#*  |  |--.|  |.---.-..----.|  |--.|   __ \.---.-..-----.|  |_|  |--..-----..----.    |       |     __|  *
#*  |  _  ||  ||  _  ||  __||    < |    __/|  _  ||     ||   _|     ||  -__||   _|    |   -   |__     |  *
#*  |_____||__||___._||____||__|__||___|   |___._||__|__||____|__|__||_____||__|      |_______|_______|  *
#* http://www.blackpantheros.eu | http://www.blackpanther.hu - kbarcza[]blackpanther.hu * Charles Barcza *
#*************************************************************************************(c)2002-2021********

## Written by Charles Barcza for blackPanther OS
## kbarcza@blackpanther.hu  *  www.blackpanther.hu
# Default KDE integration autodetect
 . /etc/bubblemsg.conf
#
dbg()
{
    	  if [ -n "$DEBUG" ]; then
       	echo
       	$SETCOLOR_FAIL
       	echo -e "DBG: ${@}"
       	$SETCOLOR_NORMAL
       	echo
    	  fi
}

chkint() {
dbg "Integration: $KDEINTEGRATION" 
if [[ "$KDE_FULL_SESSION" = "true" ]]&&[[ ! -n "$KDEINTEGRATION" ]]; then
#if [[ -n "$KDE_FULL_SESSION" ]]&&[[ ! -n $KDEINTEGRATION ]]; then
    KDEINTEGRATION="auto"
    dbg "KDE SESSION: TRUE"
elif [[ -f "$LOCKFILE" ]];then
    dbg "EXTERNAL LOCK: TRUE"
    KDEINTEGRATION=`cat $LOCKFILE | sed 's|KDEINTEGRATION=||'`   
elif [[ ! -n "$KDE_FULL_SESSION" ]];then
    KDEINTEGRATION="no"
fi
}

chmod 666 $LOCKFILE 2>/dev/null

for lockapp in kpackagekit rpmanager gpk-application ;do 
  CPS="ps -C $lockapp --format args --noheaders"
    if $CPS | grep $lockapp > /dev/null 2>&1; then
	exit
    fi
done

A="The"
ITITLE="New Application(s) Install.."
IMSG="install over successfully"
UTITLE="Application(s) Update.."
UMSG="update over successfully"
RMTITLE="Application(s) Uninstall.."
RMMSG="remove over successfully"
ERRMSG="An Error occurred.."
WARNMSG="Warning/Iportant Message!"
OTHMSG="Action.."
RUNMSG="Running now!"
SYSMSG="System message"

case $LANG in
	hu* )
	    A="A[z]"
	    ITITLE="Programtelepítés.."
	    IMSG="telepítése sikeresen befejeződött"
	    UTITLE="Programfrissítés.."
	    UMSG="frissítése sikeresen befejeződött"
	    RMTITLE="Pogrameltávolítás.."
	    RMMSG="eltávolítása sikeresen befejeződött"
	    OTHMSG="Művelet.."
	    ERRMSG="Egy hiba történt.."
	    WARNMSG="Figyelmeztetés/Fontos értesítés!"
	    RUNMSG="Futtat most!"
	    SYSMSG="Rendszerüzenet"
esac

NOTIFYSENDINTEGRATION="auto"
SETCOLOR_FAIL="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
version="0.9"
sroot=/usr
iroot=$sroot/share
itheme=$iroot/icons/blackPantherOS
isize=32x32
ipath=$itheme/$isize
ICON=$3
daemon=bubbled

if [ -z $ICON ]
then
#ICN_NORMAL=$ipath/actions/messagebox_warning.png
#ICN_LOW=$ipath/actions/messagebox_info.png
#ICN_CRITICAL=$ipath/actions/messagebox_critical.png
#ICN_NORMAL=security-high
#ICN_LOW=security-medium
#ICN_CRITICAL=security-low
ICN_NORMAL=dialog-positive
ICN_LOW=dialog-information
ICN_CRITICAL=dialog-warning
else 
ICN_NORMAL=$ICON
ICN_LOW=$ICON
ICN_CRITICAL=$ICON
fi
#echo "--------$ICON -------"
#ICN_LOW=${2}.png
ICN_INST=$ipath/actions/messagebox_critical.png
ICN_UPGR=$ipath/actions/messagebox_critical.png
ICN_UNIST=$ipath/actions/messagebox_critical.png


dohelp=0
su_user=0
users=
user=$LOGNAME
timeout=10000 # 10 seconds
timeout=6000 # 10 seconds
priority=low # low normal or critical




if [ $UID = 0 ]; then
 su_user=1
[ ! -n "$user" ] && user=$(ps -eo uname:20,cmd | grep -v grep | grep '/bin/dbus-launch' | awk '{print $1}' | sed 's|+||' 2>/dev/null)

if [ "$(echo $user |grep '^[a-zA-Z]')" = "" ];then
    dbg "Not named user, get from group id"
    usernum=`echo "$user" | grep '^[0-9]'`
    for anuser in `cat /etc/group | grep "$usernum" | awk -F: '{ print $1}'` ;do 
	users="$anuser $(echo "$user" | sed "s|$usernum||" | uniq)"
    done
 else
    dbg "Great this is a named user"
    users=$(echo $user | sed 's|dbus-launch||')
fi
 if [ "x$users" == "x" ]; then
  echo "Not connected X users"
  echo "    NOTIFICATION: $title"
  echo "         $text"
  exit 0
 fi
fi

while getopts "u:t:p:x:w:hd" flag
do
  case "$flag" in
      '?')
          dohelp=1
          ;;
      'd') 
          DEBUG=1
	# Debugging Flag
          ;;
      'dd') 
          DEBUG=1
	# Big Debugging Flag
          set -x
          ;;
      'h')
          dohelp=1
          ;;
      'u')
          user="$OPTARG"
          ;;
      'p')
          priority="$OPTARG"
          ;;
      't')
          timeout=$(($OPTARG+0))
          ;;
      'x')
          cmd="$OPTARG"
          ;;
      'w')
          wmd="$OPTARG"
          ;;
  esac
done


# Push the parsed flags off the stack so we can get to title and text
shift $((OPTIND-1)); OPTIND=1

if [ $dohelp != 0 ]; then
    clear
    cat <<EOF >&2


 ------- Send a message to notification service via DBUS -------
# More blackPanther OS commands built-in available in BubbleMSG #

 Standard options:
    usage: $0 "MSG Header" "Long Message.."
	    (example: $0 "Welcome Dear $USER" "Example System Message First Start Now...." )

 Advanced options:

    usage: $0 [install] [uninstall] [upgrade] "applicationname" 
	    (example: $0 install gimp)
    usage: $0 [error] [other] "showed message" 
	    (example: $0 error "Example Installation Error")

 Expert options:
    usage: $0 [-t timeout] [-u user] [-p priority] title [text] [-x appname]

    -t timeout     duration of the notification in seconds [default: 20000]
    -p priority    color of notification can be low normal or critical [default: normal]
    -u user        user to notify [defaults to you: $(whoami)]
    -x running	   app run after install
    -d 		   debug messages
    -dd		   better debug
    -h             this help

If text isn't specified, then title is used.
EOF
    exit 1
fi

# get the title and text
title=$1
text=$2

if [ ! -z $cmd ]&&[ -z $wmd ]
then
    wmd1="Run1 $cmd"
    wmd2="Desktop icon"
    cmd1="-n \"$wmd1\" -x \"$cmd\""
    cmd2="-n \"$wmd2\" -x \"$dskt\""
    cmds="$cmd1 $cmd2&"
 else
    cmd=$text
    wmd1="Run2 $cmd"
    cmd1="-n \"$wmd1\" -x \"$cmd\""
    #cmds="$cmd1 $cmd2&"
    cmds=""
fi

if [ -z "$title" ]; then
    echo "error: You need to give me a title" >&2
    dohelp=1
fi
if [ -z "$text" ]; then
    text=$title
fi

# Check the timeout
if [ -z "$timeout" ]; then
    echo "error: Timeout must be a number" >&2
    dohelp=1
fi

#dskicn=`rpmquery -il $cmd | grep $cmd.desktop`
#ret=$?		# if 0 available desktop file ot 1 skip copy to user desktop
#dskcmd="" 	# needed command

#cp -f $dskicn $HOME/Desktop

# Collect the dbus addresses
declare -a dbuses
pushdbus() {
  if [ -z "$1" ]; then
      return # nothing to push
  fi
  for dbus in "${dbuses[@]}"; do
      if [ "${dbus}" = "$1" ]; then
          return # It's a duplicate
      fi
  done
  dbuses[${#dbuses[@]}]="$1"
  # need to run from crontab
  export DBUS_SESSION_BUS_ADDRESS="$1"
}

dbg "pushdbus : ${DBUS_SESSION_BUS_ADDRESS}"
# Default environment, if it exists
pushdbus "${DBUS_SESSION_BUS_ADDRESS}"
#pushdbus "${KONSOLE_DBUS_SESSION}"

for user in $users; do
# Gnome
for pid in $(pgrep -u $user gnome-session); do
í    # find DBUS session bus for this session
    pushdbus `grep -z DBUS_SESSION_BUS_ADDRESS \
             /proc/$pid/environ | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//'`
done
# X-Session
#for pid in $(pgrep -u $user x-session); do
for pid in $(pgrep -u $user dbus-launch); do
    # find DBUS session bus for this session
    pushdbus `grep -z DBUS_SESSION_BUS_ADDRESS \
             /proc/$pid/environ | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//'`
done

done

while [ $# -gt 0 ]
do
chkint
 case $1 in
  install )
    title="$ITITLE"
    if [ "$KDEINTEGRATION" = "yes" ]||[ "$KDEINTEGRATION" = "auto" ];then
    text="$A $2 $IMSG"
    else
    text="$A <b>$2</b> $IMSG"
    fi
    PIC=$2
    cmds="-x $2 -n '$RUNMSG'"
   shift
   ;;
  uninstall )
    title="$RMTITLE"
    text="$A $2 $RMMSG
    "
    cmds=""
    PIC=$2
   shift
   ;;
  upgrade )
    title="$UTITLE"
    text="$A $2 $UMSG
    "
    PIC=$2
    cmds=""
   shift
   ;;
  error )
    title=${ERRMSG}
    text="$2 $3"
    priority="critical"
   shift
   ;;
  warning )
    title=${WARNMSG}
    text="$2 $3"
    priority="normal"
   shift
   ;;
  other )
   title=${OTHMSG}
   text="$2"
   #MESSAGE="$2 $3"
   cmds="$3"
   shift
   ;;
 esac
 shift
done

case $priority in
 normal)
  ICON=$ICN_NORMAL
  PICON=security-high-symbolic
  ;;
 low)
  ICON=$ICN_LOW
  PICON=security-medium-symbolic
  ;;
 critical)
  ICON=$ICN_CRITICAL
  PICON=security-low-symbolic
  ;;
 *)
  LEVEL="normal"
  #ICON=$ICN_LOW
  ;;
esac

dbg "(1)$ICON"

if [ ! -f "$ICON" ]
then
    dbg "(2)$ICON"
    if [ ! -n "$PIC" ];then 
    PIC=dialog-information
    dbg "*** find ($PIC) ***"
    src=`find /usr/share/icons/hicolor/scalable -type f -name "${PIC}.svg" | head -n 1`
    else
    dbg "*** find ($PIC) ***"
    src=`find /usr/share/icons/hicolor/32x32/ -type f -name "${PIC}.svg" | head -n 1`
    fi
    dbg "Hmm.. not found... find $PIC icon in other source "
    if [ ! -f "$src" ];then
    	    src=`find /usr/share/icons/large -type f -name "${PIC}.png" | head -n 1`
    	    dbg "Opss! not  here..find $PIC icon alternate path $src"
	    if [ ! -n "$src" ]&&[ "$title" = "$ITITLE" ]&&[ "$UID" = "0" ];then
    		#src=`find /usr/share/icons/ -type f -name "${PIC}.png" | head -n 1`
    		src=`locate "${PIC}.png" | grep '/usr/share/icons' | \
    		sed -e 's|\(.*\)16\(.*\)||' -e 's|\(.*\)22\(.*\)||' -e 's|\(.*\)128\(.*\)||'| grep ${PIC} | head -n 1`
    		dbg "*** Ajaj! ($src) ***"
    	    else
    	    ICON=$PICON
	    fi
    fi
    if [ -f "$src" ]	#&&[ ! -n "$ICON" ]
    then
	dbg "2:[$ICON]"
	dbg "3:[$src]"
	ICON=$src
	OICN="-i ${ICON}"
    else	
	OICN=" -i ${ICON}"
    fi
 else
	OICN=""
	dbg "-- skip icon discovery --"
fi

dbg "----------- $OICN --------------"
dbg "----------- $ICON --------------"

dbg "$daemon $OICN -u $priority -t $timeout -s $title -C $text"
#KDEINTEGRATION=no

if [ "$NOTIFYSOUND" != "no" ] && [ ! -f "$NOTIFYSOUND" ] && [ "$NOTIFYSOUND" = "yes" ];then
    if [ -f "/usr/share/sounds/freedesktop/stereo/service-login.oga" ];then
	sndfile=/usr/share/sounds/freedesktop/stereo/service-login.oga
    elif [ -f "/usr/share/sounds/freedesktop/stereo/device-added.oga" ];then
	sndfile=/usr/share/sounds/freedesktop/stereo/device-added.oga
    fi
 else
    sndfile=$NOTIFYSOUNDFILE
fi
    if (pidof pulseaudio &>/dev/null) ; then
	player="paplay -p"
    else
	player="play -q"
    fi

dbg "Player: $player File: $sndfile"

if [ $su_user = 1 ]; then
dbg "su_user state"
 for user in $users; do
    #chkint $user
    #KDEINTEGRATION=`cat /tmp/.kintegration.lock | sed 's|KDEINTEGRATION=||'`
    #kdialog --msgbox "$USER - $HOME -  $user - $KDE_FULL_SESSION - $KDEINTEGRATION"
    if [ "$KDEINTEGRATION" = "yes" ]||[ "$KDEINTEGRATION" = "auto" ]&&[ -x "$(which kdialog 2>/dev/null)" ];then
    dbg "1 KDE INTEGRATION ON"
    echo ""
    OICN=$(echo $OICN| sed -e 's|-i ||')
    xmsg=$(which kdialog 2>/dev/null || which pydialog 2>/dev/null)
    su -c "$xmsg --title '$title' --icon  $OICN --passivepopup '$text' 9" $user &#2>/dev/null
    dbg "$xmsg --title '$title' --icon  $OICN --passivepopup $text' 9 $user"
    else
    dbg "KDE INTEGRATION OFF"
	if [ -x /usr/lib/notify-osd/notify-osd ];then
	    dbg "OSD INTEGRATION ON"
	    su -c "$daemon -u $priority $OICN -t $timeout '$title' '$text' " $user &#2>/dev/null
	elif [ "$NOTIFYSENDINTEGRATION" = "yes" ]||[ "$NOTIFYSENDINTEGRATION" = "auto" ];then
	    dbg "NOTIFYSEND INTEGRATION ON"
	    su -c "notify-send -a 'blackPanther $SYSMSG' $OICN '$title' '$text'" $user &#2>/dev/null
	    #su -c "notify-send -i '$PICON' '$title' '$text'" $user &#2>/dev/null
	    dbg "su -c notify-send -a \"blackPanther $SYSMSG\" $OICN \"$title\" \"$text\"  $user" #2>/dev/null
	 else
	    dbg "OTHER INTEGRATION ON"
	    su -c "$daemon -u $priority $OICN -t $timeout '$title' '$text' $cmds" $user &#2>/dev/null
	    dbg "su -c \"$daemon -u $priority $OICN -t $timeout \"$title\" \"$text\" $cmds $user" #2>/dev/null    
        fi
    fi
        dbg "$NOTIFYSOUND $player $sndfile"

        if [ $NOTIFYSOUND != no ]&&[ -n "$player" ]&&[ -f "$sndfile" ];then
    	    for i in $user ;do
    	    ID=$(id -u $i)
    	    done

    	    dbg "XDG_RUNTIME_DIR=/run/user/$ID /usr/bin/$player $sndfile $(id -u $ID -n)" 
	    su -c "XDG_RUNTIME_DIR=/run/user/$ID /usr/bin/$player $sndfile" $(id -u $ID -n) &
	fi
    
  if [ $? != 0 ]; then
    echo "NOTIFICATION: $title"
    echo "$text"
    exit
  fi
 done
 exit
fi

if [ -n "$DBUS_SESSION_BUS_ADDRESS" ];then
for dbus in "${dbuses[@]}";
do
  # Disabled for PyDialog development finish
  #xmsg=$(which kdialog 2>/dev/null || which pydialog 2>/dev/null)
  if [ "$KDEINTEGRATION" = "yes" -o "$KDEINTEGRATION" = "auto" ]&&[ -x "$(which $xmsg 2>/dev/null)" ];then
    dbg "DBUS YES! / KDE INTEGRATION ON!"
    echo ""
    [ "$UID" = "0" ]&&su -c "$xmsg --title '$title' --passivepopup '$text<br>' 9" $user &#2>/dev/null
    [ "$UID" != "0" ]&& $xmsg --title "$title" --passivepopup "$text<br>" 9 &#2>/dev/null
   else
    dbg "DBUS ON / KDE INTEGRATION OFF"
	if [ -x /usr/lib/notify-osd/notify-osd ];then
	    dbg "DBUS OSD INTEGRATION ON"
	    $daemon -u $priority $OICN -t $timeout "$title" "$text"
	elif [ -x $(which notify-send) ];then
	    dbg "DBUS NOTIFYSEND INTEGRATION ON"
	    env DBUS_SESSION_BUS_ADDRESS="${dbus}" notify-send -a "blackPanther $SYSMSG" -i $PICON -u $priority -t $timeout "$title" "$text" &
	    dbg "$daemon -u $priority $OICN -t $timeout \"$title\" \"$text\""
	 else
	    dbg "DBUS OTHER INTEGRATION ON"
	    $daemon -u $priority $OICN -t $timeout '$title' '$text' $cmds
	    dbg "$daemon -u $priority $OICN -t $timeout \"$title\" \"$text\" $cmds"
        fi
  fi
    dbg "dbus state"
done

else
	    [ ! -n "$OICN" ]&& OICN=$PICON
	    dbg "Temporary DBUS address problem.  USE ATHER INTEGRATION"
	    $daemon -u $priority $OICN -t $timeout "$title" "$text" $cmds &
	    dbg "$daemon -u $priority $OICN -t $timeout \"$title\" \"$text\" $cmds"

fi
dbg "$NOTIFYSOUND && $player && $sndfile"
if [ $NOTIFYSOUND != no ]&&[ -n "$player" ]&&[ -f "$sndfile" ]&&[ -n "$DISPLAY" ];then
        #dbg "XDG_RUNTIME_DIR=/run/user/$ID /usr/bin/$player $sndfile $(id -u $ID -n)"
        #XDG_RUNTIME_DIR=/run/user/$ID /usr/bin/$player $sndfile $(id -u $ID -n) &  
        dbg "/usr/bin/$player $sndfile"
        /usr/bin/$player "$sndfile" &
fi

rm -f $LOCKFILE 2>/dev/null
echo
exit
