#!/bin/bash

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

# Translations only work with utf8 locales
if [ ! `echo $LANG | grep -i utf` ]; then
	LANG=C
fi

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

# Determine if gksu or kdesu will be used
if [[ `which gksu 2> /dev/null` ]]; then
	SUCOMMAND="gksu"
elif [[ `which ktsuss 2> /dev/null` ]]; then
	SUCOMMAND="ktsuss -u root"
elif [[ `which kdesu 2> /dev/null` ]]; then
	SUCOMMAND="kdesu"
else
	echo "`eval_gettext 'ERROR: gksu, ktsuss or kdesu are required for salix-update-notifier to work.'`" >&2
	exit 1
fi

# Check if matedialog is present
if [[ ! `which matedialog 2> /dev/null` ]]; then
	echo "`eval_gettext 'ERROR: matedialog must be installed for salix-update-notifier to work.'`" >&2
	exit 1
fi

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

# Main loop
while true; do
	if [[ `LANG=C /usr/sbin/slapt-get -s --upgrade | grep "Need to get"` ]]
	then
		matedialog --notification \
		--text="`eval_gettext 'Package updates are available.'`" \
		--window-icon=/usr/share/pixmaps/salix-update-notifier.png \
		&& matedialog --question \
		--title "`eval_gettext 'Install package updates?'`" \
		--text="`eval_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?'`" \
		--window-icon=/usr/share/pixmaps/salix-update-notifier.png \
		&& $SUCOMMAND gslapt --upgrade
	fi

	# Check if there is a config file that sets a different interval
	# than the default and use that
	if [ -f $HOME/.config/salix-update-notifier ]; then
		INTERVAL=`grep "^interval=" $HOME/.config/salix-update-notifier | \
		head -n1 | sed "s/interval=\(.*\)/\1/" `
	elif [ -f /etc/salix-update-notifier.conf ]; then
		INTERVAL=`grep "^interval=" /etc/salix-update-notifier.conf | \
		head -n1 | sed "s/interval=\(.*\)/\1/" `
	else
		INTERVAL=$DEFAULT_INTERVAL
	fi
	# Wait until checking for updates again
	sleep $INTERVAL || sleep $DEFAULT_INTERVAL
done

