#!/bin/bash

# Done by Joel Wiesmann, June 2003 as a part of the stable Debian + vserver HOWTO
# License is GPL, of course ;)

# USE:
# Use this script to manage the distributed upgrades of the base
# vserver to all vserver childs. Just do your settings in this 
# script and run it!

# ATTENTION:
# This script is a part of the vserver + debian HOWTO. So if
# you like to use this script in a useful way, you should have
# set up the server with the HOWTO instructions.

VSERVERS=/vservers
TMPDIR=/tmp
REFERENCE=base
# This is done manually because we could have testing/unstable servers we don't want to upgrade
# this way
UPGRADESERVERS="base pizzaman trader slave"

# First time you test this script choose LOGGING=no to see output, afterwards if
# you do a cronjob with it, choose LOGGING=yes to log in the files below
# Don't be iritated by the ERROR(FILE), it also records what Packages were updated.
LOGGING=no
ERRORFILE=/var/log/vserversoftdistr.err

function main
{
	# Delete old, archived .deb files
	rm $VSERVERS/$REFERENCE/var/cache/apt/archives/*.deb 2>> $ERRORFILE

	# Update the reference-system-db and download the packages
	vserver $REFERENCE exec apt-get update 2>> $ERRORFILE
	vserver $REFERENCE exec apt-get -yd upgrade 2>> $ERRORFILE

	# Now we have all up2date .deb's in $VSERVERS/$REFERENCE/var/cache/apt/archives
	# let's install them into the child-vservers. The reference-server
	# get's upgraded in this procedure too!
	for i in `ls $VSERVERS/$REFERENCE/var/cache/apt/archives/*.deb`
 	do
		echo "Upgrading Package $i" >> $ERRORFILE
		installpkg $i
 	done
}

function installpkg
{
	PACKAGEPATH=$1
	PACKAGE=`basename $PACKAGEPATH`
	for i in `UPGRADESERVERS`
	do
		SERVER=$i
		# Check if noone tries to do something nasty
		if [ -e "$VSERVERS/$SERVER/$TMPDIR/$PACKAGE" ]
		then
			echo "$PACKAGE is already in tmp-directory of vserver $SERVER. I won't install it." >> $ERRORFILE
		else
			cp $PACKAGEPATH $VSERVERS/$SERVER/$TMPDIR 2>> $ERRORFILE
			vserver $SERVER exec dpkg --install /tmp/$PACKAGE 2>> $ERRORFILE
			rm $VSERVERS/$SERVER/$TMPDIR/$PACKAGE 2>> $ERRORFILE
		fi
	done
}

if [ "$LOGGING" == "no" ]
then
	ERRORFILE=/dev/stderr
fi

main
