#! /bin/bash

# Redirect output to a log file
exec > /var/log/updates.log 2>&1

# Add GPG keys for verifying packages
for key in /usr/local/keys/*.key; do
	gpg --import < "${key}" >/dev/null 2>/dev/null
done

# Output date information
echo ""
echo " *** Automatic Update started in $(date)"
echo ""

# Check for updates to slapt-get first.
slapt-get --clean >/dev/null 2>/dev/null
slapt-get --update || exit 1 >/dev/null 2>/dev/null
if slapt-get --print-uris --upgrade | grep 'tp://' | grep '/slapt-get-' >/dev/null; then
	# Update the updater first
	(
		UPGRADETMPDIR="${TMPDIR:-/tmp}/automatic-update-$$${RANDOM}${RANDOM}${RANDOM}"
		mkdir -p "${UPGRADETMPDIR}" || exit 1
		cd "${UPGRADETMPDIR}" || exit 1

		wget $(slapt-get --print-uris --no-dep --install slapt-get | grep 'tp://.*\.tgz')
		upgradepkg *.tgz

		rm -rf "${UPGRADETMPDIR}"
	)
fi

# Perform updates
slapt-get --clean >/dev/null 2>/dev/null
slapt-get --update || exit 1
slapt-get --no-prompt --upgrade || exit 1
slapt-get --clean >/dev/null 2>/dev/null

# If updates were sucessful, restart public services
if [ -x /etc/rc.d/rc.sshd ]; then
	/etc/rc.d/rc.sshd restart
fi
