#!/bin/bash
# Copyright (C) 2008 Richard Hughes <richard@hughsie.com>
#
# Some material taken from yum-cron, Copyright 2007 Alec Habig <ahabig@umn.edu>
#
# Licensed under the GNU General Public License Version 2
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

[ -f /etc/sysconfig/packagekit-background ] && . /etc/sysconfig/packagekit-background

# are we disabled?
if [ "$ENABLED" = "no" ]; then
	exit 0
fi

# set default for SYSTEM_NAME
[ -z "$SYSTEM_NAME" ] && SYSTEM_NAME=$(hostname)

PKTMP=$(mktemp /var/run/packagekit-cron.XXXXXX)
PKCON_OPTIONS="--background --noninteractive --plain"

# wait a random amount of time to avoid hammering the servers
[ -z "$SLEEP_MAX" ] && SLEEP_MAX=$RANDOM
sleep $(( $RANDOM % $SLEEP_MAX + 1 ))

# do action
if [ "$CHECK_ONLY" = "yes" ]; then
	pkcon $PKCON_OPTIONS get-updates &> $PKTMP
	PKCON_RETVAL=$?
else
	pkcon $PKCON_OPTIONS update &> $PKTMP
	PKCON_RETVAL=$?
fi

# this is when seomthing useful was done
if [ $PKCON_RETVAL -ne 5 ]; then
	# send email
	if [ -n "$MAILTO" ]; then
		mail -s "System updates available: $SYSTEM_NAME" $MAILTO < $PKTMP
	else
		# default behavior is to use cron's internal mailing of output from cron-script
		cat $PKTMP
	fi
fi

rm -f $PKTMP

