#!/bin/sh

# sleep for a random interval of time (default 30min)
# (some code taken from cron-apt, thanks)

random_sleep()
{
    RandomSleep=1800

    if [ -z "$RANDOM" ] ; then
	# A fix for shells that do not have this bash feature.
	RANDOM=$(dd if=/dev/urandom count=1 2> /dev/null | cksum | cut -c"1-5")
    fi
    TIME=$(($RANDOM % $RandomSleep))
    sleep $TIME
}

# laptop check, on_ac_power returns:
#       0 (true)    System is on mains power
#       1 (false)   System is not on mains power
#       255 (false) Power status could not be determined
# Desktop systems always return 255 it seems
if which on_ac_power >/dev/null; then
	on_ac_power
	if [ $? -eq 1 ]; then
		exit 0
	fi
fi

# sleep random amount of time to avoid hitting the 
# mirrors at the same time
###random_sleep

# check if we can access the cache
if ! apt-get check -q -q 2>/dev/null; then
	# wait random amount of time before retrying
	random_sleep
	# check again
	if ! apt-get check -q -q 2>/dev/null; then
		echo "$0: could not lock the APT cache while performing daily cron job. "
		echo "Is another package manager working?"
		exit 1
	fi
fi

# check for a new archive signing key (against the master keyring)
### apt-key net-update ### in other release

# now run the update
if apt-get -qq update 2>/dev/null; then
	# Could possible test access to '/var/run/dbus/system_bus_socket' has well,
	# but I'm not sure how stable the internal pipe location is defined as
	# being;  so for the moment just 2>/dev/null . --sladen 2007-09-27

	if which dbus-send >/dev/null; then
		dbus-send --system / app.apt.dbus.updated boolean:true 2>/dev/null || true
	fi

	# now run apt-xapian-index if it is installed to ensure the index
	# is up-to-date
###	if [ -x /usr/sbin/update-apt-xapian-index ]; then
###	    ionice -c3 update-apt-xapian-index -q
###	fi
fi
