#!/bin/sh
####################################################################
# 95turboprint_monitor
#
# script to be started with user login by xwindows xinit.rc
# (wayland has no global login script)
# or by systemd global user service (not yet reliable)
# (c) ZEDOnet GmbH
# ATTENTION: xinit.rc starts this script always with sh, not bash
#            expressions like ${HOME:0:8} not available
####################################################################

###
# create communication pipes if necessary
###
eval $(cat /etc/turboprint/system.cfg)

LOGFILE="$TPPATH_LOG/turboprint/install.log"
echo "#######################################################" >> "$LOGFILE"
echo "95turboprint_monitor started $(date) user=$USER home=$HOME" >> "$LOGFILE"

###
# exit if not started as user $HOME starts with /var/lib
###
HOME_PREFIX=$( expr "$HOME" :  '\(.\{8\}\)' )
if [ $HOME_PREFIX = "/var/lib" ] ; then
	echo "systemd started the service not a regular user, returning" >> "$LOGFILE"
else
###
# create comminication pipes from filter to daemon
###
"$TPPATH_FILTERS/pipeutility" 

###
# add entry to .config/autostart to open turboprint-monitor
# make sure that home directory exists
###
if [ -e "$HOME" ] ; then
  echo "creating $HOME/.turboprint, adding autostart and autostart-scripts" >> "$LOGFILE"
  mkdir ~/.turboprint &>> $LOGFILE
  mkdir -p ~/.config/autostart &>> $LOGFILE
  TP_ENTRY="/home/$USER/.config/autostart/turboprint-monitor.desktop"

  echo > $TP_ENTRY "[Desktop Entry]"
  echo >> $TP_ENTRY "Type=Application"
  echo >> $TP_ENTRY "Exec='$TPPATH_FILTERS/turboprint-startmonitor'"
  echo >> $TP_ENTRY "Icon=turboprint-applet"
  echo >> $TP_ENTRY "MapNotify=true"
  echo >> $TP_ENTRY "DocPath=$TPPATH_DOC/html/turboprint.html"
  echo >> $TP_ENTRY "Comment=Monitor TurboPrint printers"
  echo >> $TP_ENTRY "Terminal=0"
  echo >> $TP_ENTRY "Name=TurboPrint Monitor"
  echo >> $TP_ENTRY "Categories=System;Monitor;"
  # autostart script for KDE 5
  mkdir -p ~/.config/autostart-scripts
  cp "$TPPATH_FILTERS/turboprint-startmonitor" ~/.config/autostart-scripts
fi
fi

###
# finished
###
echo "95turboprint_monitor terminates" >> "$LOGFILE"

###
# exit would log out user
###
#exit 0
