#!/bin/bash

# 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"
. gettext.sh

# Check if ktsuss is present
if [[ ! `which ktsuss 2> /dev/null` ]]; then
	echo "`eval_gettext 'ERROR: ktsuss 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
A=$(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?'|sed 's/\\n/\n/g')
while true; do
	if [[ `LANG=C /usr/sbin/slapt-get -s --upgrade | grep "Need to get"` ]]
	then
		/usr/libexec/salix-update-notifier-tray-icon \
		&& yad --notication \
		--title "`eval_gettext 'Install package updates?'`" \
		--text="$A" \
		--image=/usr/share/pixmaps/salix-update-notifier.png \
		--icon-size 32 \
		&& /usr/bin/ktsuss -u root "/usr/sbin/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

