#!/bin/bash

# ServicesUI - allow programs working with higher privileges to interact with users
# Copyright (C) 2020  Lach Sławomir <slawek@lach.art.pl>
#  
# This program 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.
# 
# This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.


mode=none
bus_name=""
cookie=""

"Bonsole"  --system-bus  "--show-dbus-name" "--set-cookie-for-autoconnect" "--auto-auth-with-global-cookie" "--hide-main-window" |
( while read a; do 
  if [ x"$mode" == x"none" ]; then
    if [ x"$a" == x"DBUS connection's name is:" ]; then 
      mode="bus_name" 
    elif [ x"$a" == x"Cookie for autoconnect is:" ]; then
      mode="cookie"
    fi
  
   
  elif [ x"$mode" == x"bus_name" ]; then
  
     bus_name="$a"
     mode="none"
  elif [ x"$mode" == x"cookie" ]; then
      
     cookie="$a"
     mode="none"
  fi
  
  if [ x"$bus_name" != x"" ] && [ x"$cookie" != x"" ]; then
    
    mode="done"
    # sending info
    
    dbus-send  --reply-timeout=9999999999999 --print-reply --system --dest=pl.art.lach.slawek.apps.DaemonUI  --type=method_call "/pl/art/lach/slawek/apps/DaemonUI" "pl.art.lach.slawek.apps.DaemonUI.listener.register" string:$bus_name string:$cookie 
    dbus-monitor --system type='signal',sender='pl.art.lach.slawek.apps.DaemonUI',interface='pl.art.lach.slawek.apps.DaemonUI.daemon',member='Created' | ( read a; read a; while read a; do  dbus-send  --reply-timeout=9999999999999 --print-reply --system --dest=pl.art.lach.slawek.apps.DaemonUI  --type=method_call "/pl/art/lach/slawek/apps/DaemonUI" "pl.art.lach.slawek.apps.DaemonUI.listener.register" string:$bus_name string:$cookie 
    done )
    fi
done )
