#!/bin/sh
# Script to update a debian installation...
# (C) 2000-2004 Fabien Niņoles <fabien@tzone.org>
#   Distributed under the GNU GENERAL PUBLIC LICENSE.
# This script is a mess and can be really clean up.

# Special config file for
INSTALLFILE=/etc/apt/apt-update.conf
FAILED=0
WARNME=1
GETCONTENT=0
CONTENT_SRC_URL="http://http.us.debian.org/debian/dists/unstable/Contents-i386.gz"
CONTENT_DEST_URL="/usr/archives/debian/dists/unstable/Contents-i386.gz"

eval `apt-config shell ARCHPATH Dir::Cache::archives/d`

# Some utilities

lastarg () {
  eval "echo \$$#"
}

remaining() {
  echo $* | rev | cut -d\  -f 2- | rev
}

uncommentme () {
	file=`lastarg $*`
	command=`remaining $*`
	if [ -r $file ]
	then
		if grep -q -v '^(#.*)?[ \t]*$' $file
		then
			$command `egrep -v '^(#.*)?[ \t]*$' $file | \
				sed -e 's/#.*//'`
		fi
	fi
}

getmypackageslists () {

	aptitude update > /dev/null

}

getmycontentlist () {
	if test -x /usr/bin/wget ; then
		/usr/bin/wget -nv -S -N \
			$CONTENT_SRC_URL \
			-O $CONTENT_DEST_URL > /dev/null 2>&1 
	fi
}

listchangelog () {

	if ls $ARCHPATH | grep -qe '\.deb$' ; then
		if test -x /usr/bin/apt-listchanges ; then
			apt-listchanges -f text $ARCHPATH/*.deb 2>/dev/null
		else
			echo Current files to install:
			ls $ARCHPATH | grep -e '\.deb$'
			echo
			echo Run apt-get clean after installed them to avoid this message again.
		fi
	fi

}

# Script main functions

updateme () {
	# Get new packages lists
	apt-get update -f -y -qq || FAILED=1
	# Clean old available files
	# Only files who are no more available is erased.
	apt-get -qq -y autoclean
	# install new packages from file ~/ToInstall
	# This file contains a list of package names to be download
	# Comments are allowed by beginning the line with an '#' (no space before!).
	uncommentme apt-get -d -qq -y install $INSTALLFILE
	# Download all upgraded packages
	# If you running unstable, I suggests you to replace dist-upgrade
	# by upgrade since some packages can be missing in the archives
	# and could break your system.
	apt-get -d -qq -y dist-upgrade || FAILED=2
	# Move packages in archives
	if test -x /usr/bin/apt-move ; then
		/usr/bin/apt-move update > /dev/null 2>&1 || FAILED=3 
	fi
	# Update the packages list in dselect.
	getmypackageslists

	# This is specific to my machine...
	if [ "$GETCONTENT" = "1" ] ; then getmycontentlist ; fi

	if [ "$WARNME" = "1" ] ; then listchangelog ; fi
}

installme () {
	uncommentme apt-get install -u $INSTALLFILE
	apt-get dist-upgrade -u
}

# main procedure
if [ $# = 1 ]; then
	if [ "$1" = "install" ]; then
		installme
		exit $FAILED
	fi
fi
updateme
exit $FAILED
