#!/bin/bash
#
# 22 Jan 2014 Mike Gore

TMP=/tmp/$$.install

mkdir -p $TMP
pushd $TMP
	echo update packages
	apt-get update -q

	echo Install alien to convert rpm packages
	apt-get install alien 

	# =================== NOTE ======================
	# These files names will change with new releases
	if [ `arch` = "x86_64" ]
	then
		apt-get install --reinstall libstdc++5 libstdc++5:i386
		LEGATO=nw_linux_x86_64.tar
	else
		apt-get install --reinstall libstdc++5 
		LEGATO=nw_linux_i686.tar
	fi
	# ===============================================

	echo Downloading $LEGATO
	wget -nc http://ist.uwaterloo.ca/download/networker/current/$LEGATO
	echo Extracting $LEGATO RPM files
	tar xf $LEGATO

	for i in *.rpm
	do
		echo Convert RPM $i to debian packages and install
		alien --to-deb -i --scripts $i
	done

	echo stopping networker
	/etc/init.d/networker stop

	echo removing old startup links
	update-rc.d networker -f /etc/rc?.d/*networker*

	if [ ! -f /etc/init.d/networker ]
	then
		echo /etc/init.d/networker is missing
		exit 1
	fi

	echo Modify netwoker startup scripts
	if ! grep backup.cs.uwaterloo.ca /etc/init.d/networker >/dev/null 2>&1
	then
		sed -i /etc/init.d/networker -e "s/\"\/usr\/sbin\/nsrexecd\"/& -s backup.cs.uwaterloo.ca/" 
	fi

	echo creating new startup links
	rm -f /etc/rc?.d/*networker*
	update-rc.d networker defaults 80

	echo starting networker
	/etc/init.d/networker start

	echo You should see the task nsrexecd running
	ps ax | grep nsrexecd
popd

if [ -n "$TMP" ]
then
	rm -rf "$TMP"
fi