#!/bin/bash
PATH=/usr/bin:/bin:/usr/lib

PRGNAME=$(basename $0)

. /etc/sysconfig/autoupdate

[[ $AUTOUPDATE_ENABLE != yes ]] && {
	exit
}

# are we online?
ONLINE=no
while [ ${AUTOUPDATE_TRIES:=5} -gt 0 ]; do
	case $(ping -qnc 1 ${AUTOUPDATE_SERVER:=ftp.gwdg.de} 2>&1) in

	*'100% packet loss'|\
	*'unknown host'*)

		AUTOUPDATE_TRIES=$(($AUTOUPDATE_TRIES - 1))
		;;
	*)
		ONLINE=yes
		break
	esac

	# Don't wait to long, as other scripts in the
	# cron.daily directory will be blocked...
	sleep ${AUTOUPDATE_RETRY_TIME:=120}
done

MAIL_HEADER="To: ${AUTOUPDATE_MAILTO:=root}
From: $PRGNAME <root>"

[[ ONLINE == no ]] && {
	( echo "$MAIL_HEADER"
	  echo "Subject: no system update, network down"
	  echo
	  echo "$PRGNAME: the automatic package update could not"
	  echo "be performed as the network was down."
	) | sendmail -t

	exit 1
}

# We are online
apt -qq update

case ${AUTOUPDATE_TYPE:=security} in
basesystem)
	TYPE=basesystem
	;;
*)
	TYPE=security
	;;
esac

# If the md5sum equals 029d6b349e0fe6da958aee3b0d346446, there
# are no packages to be updated.  The apt output is than:
# Reading Package Lists...
# Building Dependency Tree...
# 0 upgraded, 0 newly installed, 0 removed and 0 not upgraded.
apt --simulate --sources $TYPE.list upgrade > /tmp/$PRGNAME.$$

MD5SUM=$(md5sum /tmp/$PRGNAME.$$ | cut -d " " -f1)
[[ $MD5SUM != 029d6b349e0fe6da958aee3b0d346446 ]] && {
	apt -qq --yes --sources $TYPE.list upgrade

	( echo "$MAIL_HEADER"
	  echo "Subject: system update performed"
	  echo
	  grep -vE "^Reading Package Lists|Building Dependency" /tmp/$PRGNAME.$$ |
	    sed 's/^The following packages will be/The following packages have been/'
	) | sendmail -t
}

rm -f /tmp/$PRGNAME.$$

