#!/bin/sh

# The default interval is set to 2 hours
DEFAULT_INTERVAL="2h"

# Translations only work with utf8 locales
if ! locale -k charmap|grep -q UTF-8 ; then
	LANG=C
fi

# Gettext internationalization
export TEXTDOMAIN="salix-update-notifier"
export TEXTDOMAINDIR="/usr/share/locale"

# Determine if ktsuss or gksu will be used
if test "$(which ktsuss 2> /dev/null)"; then
	SUCOMMAND="ktsuss -u root"
elif test "$(which gksu 2> /dev/null)"; then
	SUCOMMAND="gksu"
else
	echo "(gettext 'ERROR: gksu or ktsuss are required for salix-update-notifier to work.')" >&2
	exit 1
fi

# Check if yad is present
if ! test "$(which yad 2> /dev/null)"; then
	echo "(gettext 'ERROR: yad must be installed for salix-update-notifier to work.')" >&2
	exit 1
fi

# Wait 10 mins before running for the first time
sleep 10m

# possible locations for the configuration file
CONFIG_FILE_LOCAL=$HOME/.config/salix-update-notifier
CONFIG_FILE_GLOBAL=/etc/salix-update-notifier.conf
unset NOTIFY
# Main loop
A=$(gettext 'Package updates are available for your system.\n\nSelecting OK will perform the updates using gslapt. Root user privileges will be required in order to do that.\n\nProceed with updating?'|sed 's/\\n/\n/g')
B=$(gettext 'Package updates are available.')
while true; do
	# Check if there is a config file that should be read
	if [ -f "$CONFIG_FILE_LOCAL" ]; then
		CONFIG_FILE="$CONFIG_FILE_LOCAL"
	elif [ -f "$CONFIG_FILE_GLOBAL" ]; then
		CONFIG_FILE="$CONFIG_FILE_GLOBAL"
	fi

	# Read configuration, includes the default interval and wheter to
	# use a notification in addition to the tray icon
	INTERVAL=$DEFAULT_INTERVAL
	if [ -n "$CONFIG_FILE" ]; then
		INTERVAL=$(grep "^interval=" $CONFIG_FILE | \
			head -n1 | sed "s/interval=\(.*\)/\1/")
		grep -q "^notification=true$" $CONFIG_FILE && \
			[ -x /usr/bin/notify-send ] && \
			NOTIFY="yes"
	fi
	if LANG=C /usr/sbin/slapt-get -s --upgrade | grep -q "Need to get"; then
	    if test "$NOTIFY"; then
			notify-send -a salix-update-notifier "$B"
		fi
		/usr/libexec/salix-update-notifier-tray-icon \
		&& yad --notification \
		--title "$(gettext 'Install package updates?')" \
		--text="$A" \
		--image=/usr/share/pixmaps/salix-update-notifier.png \
		--icon-size 32 \
		&& $SUCOMMAND "/usr/sbin/gslapt --upgrade"
	fi

	# Wait until checking for updates again
	sleep "$INTERVAL" || sleep "$DEFAULT_INTERVAL"
done

