#!/bin/sh
##################################################################
#
# Copyright (C) 2002 R Bos
#
# File:           $RCSfile: apt,v $
# Revision:       $Revision: 1.1 $
# Last change:    $Date: 2002/06/12 09:36:22 $
# Last change by: $Author: rbos $
#
# Send suggestions to: apt4rpm-devel@lists.sourceforge.net
# Homepage: http://apt4rpm.sourceforge.net
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# For a copy of the GNU General Public License, visit
# http://www.gnu.org or write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##################################################################

PATH=/bin:/sbin:/usr/sbin:/usr/bin

HOURS=$1
EMAIL=

# When was the last time that a package has been updated (in seconds)
LAST_RUN_BY_USER=$(rpm  -q --queryformat %{INSTALLTIME} $(rpm -qa --last |
  awk '{ if (NR == 1) print $1 }'))

CURRENT_TIME=$(date +%s)

if [ -s /var/run/apt.lastrun ]
then
	LAST_RUN=$(cat /var/run/apt.lastrun)
else
	LAST_RUN=0
fi

if [ $LAST_RUN_BY_USER -gt $LAST_RUN ]
then
	LAST_RUN=$LAST_RUN_BY_USER
fi

UPDATE=$(echo ${CURRENT_TIME:-1} ${LAST_RUN:-0} ${HOURS:-23} | awk '
{
	current_time=$1
        last_run = $2
        max_time = $3 * 3600
	interval = current_time - last_run
}
END {
	if ( max_time > interval ) { print "" } else { print "1" }
}')

(	if [ $UPDATE ]
	then
		# Do not immediately run at the beginning as the system
		# will be very busy setting up all kind of things.
		# Run in background as updating can take a lot of time,
		# unfortenately the user may be getting an inconsistent
		# system.

		sleep 180

		# If needed set the following 2 variables, or even better
		# define the variables in apt.conf
		# export ftp_proxy=
		# export no_proxy=

		apt-get -qq update 2> /dev/null
		apt-get -S dist-upgrade | grep from |
		  grep -v Importance | grep -v ^\$ > /tmp/autoapt.$$
		if [ -s /tmp/autoapt.$$ ]
		then
			apt-get -qq -y dist-upgrade
			apt-get clean

			# logging
			CURRENT_DATE=$(date +%x)
			mailx -s "SW upgrade result" ${EMAIL:-root} < /tmp/autoapt.$$
			sed s+^+$CURRENT_DATE:+ /tmp/autoapt.$$ >> /var/log/aptpkg.log
		fi
	        date +%s > /var/run/apt.lastrun
		rm -f /tmp/autoapt.$$
	fi
) &

