#!/bin/bash

dbuser=`/m23/bin/getMySQL-UserParam.sh`
dbadmpassParam=`/m23/bin/getMySQL-PasswordParam.sh`


# Skip restoration of packages and debconf if run on UCS
if [ ! -f '/usr/sbin/udm' ]
then
	export DEBIAN_FRONTEND=noninteractive
	apt-get update
	
	#Restore debconf
	apt-get --allow-downgrades --allow-unauthenticated -y install debconf-utils
	bzcat -d -c debconf.bz2 > /tmp/debconfm23Restore
	debconf-set-selections /tmp/debconfm23Restore
	
	#Get the difference between the installed packages of the backupped server and the current server
	dpkg --get-selections | grep -v deinstall$ | tr -d [:blank:] | sed 's/install$//g' | sort -u > /tmp/foundPKG
	bzcat -d -c packages.bz2 | sed 's/ /\n/g' | sort -u > /tmp/wantedPKG
	diff /tmp/foundPKG /tmp/wantedPKG | grep '>' | cut -d' ' -f2 > /tmp/missingPKG
	
	if [ `wc -l /tmp/missingPKG | cut -d' ' -f1` -gt 0 ]
	then
		#Install the missing packages
		for package in `cat /tmp/missingPKG`
		do
			echo -n "Trying to install $package ..."
			apt-get --allow-downgrades --allow-unauthenticated -y install $package
			echo "finished"
		done
	fi
fi


echo -n "Restoring m23 config files..."
tar -xvjf m23config.tar.bz2 -C/
echo " done"


# Check, if the IP of the backuped m23 server and the current server differ
if [ -f /tmp/serverInfoIP.txt ] && [ $(/m23/bin/serverInfoIP) != $(cat /tmp/serverInfoIP.txt) ] && [ -f '/usr/sbin/udm' ]
then
	# Get backupped (in regex save format) and new IP of the m23 server
	oldIP=$(cat /tmp/serverInfoIP.txt | sed 's/\./\\./g')
	newIP=$(/m23/bin/serverInfoIP)

	# Replace the IP in the dump
	bzcat -d -c m23.sql.bz2 | sed "s/$oldIP/$newIP/g" | bzip2 -9 -z -c > m23-new.sql.bz2
	mv m23-new.sql.bz2 m23.sql.bz2
fi


echo -n "Restoring m23 and m23captured databases..."
bzcat -d -c m23.sql.bz2 | mysql $dbuser $dbadmpassParam m23
bzcat -d -c m23captured.sql.bz2 | mysql $dbuser $dbadmpassParam m23captured
echo " done"


if [ -f kdb5.dump.bz2 ]
then
	# Stop Kerberos KDC
	service krb5-kdc stop

	echo -n "Restoring Kerberos databases..."
	bunzip2 kdb5.dump.bz2
	kdb5_util load -verbose dumpfile kdb5.dump
	echo " done"

	# Start Kerberos KDC again
	service krb5-kdc start
fi


# Skip restoration of /etc if run on UCS
if [ ! -f '/usr/sbin/udm' ]
then
	echo -n "Restoring /etc..."
	tar -xvjf etc.tar.bz2 -C/
	echo " done"
fi





dpkg-reconfigure m23
/etc/init.d/networking restart
if [ -e /etc/init.d/apache2 ]
then
	/etc/init.d/apache2 restart
fi

if [ -e /etc/init.d/apache ]
then
	/etc/init.d/apache restart
fi