#!/bin/bash
# 
# script by Fortunato Ventre (voRia) - <vorione@gmail.com> - <http://www.voria.org>
#
# Revert all packages installed from voRia's repository to the version from official Ubuntu repositories.
# Packages not available on official Ubuntu repositories will be removed (for instance, nc10-scripts).
#
# Make sure to remove the voRia's repository lines from your /etc/apt/sources.list, and use the command
# 'sudo apt-get update' to update the repositories list. Then, use this script.

# Check permissions
if [ `id -u` != 0 ]; then
	echo "Please run this script with sudo."
	exit 1
fi

# Check if voRia's repository has been disabled
if cat /etc/apt/sources.list | grep voria/ppa | grep -v "^#" > /dev/null; then
	echo "You need to remove the voRia's repository lines from your '/etc/apt/sources.list'."
	echo "Do not forget to run 'sudo apt-get update' after removing them!"
	exit 1
fi

# Check what ubuntu release are we working on
RELEASE=`lsb_release -c | awk '{print $2}'`
if [ $RELEASE = "karmic" ]; then
	VERSION_STRING="loms"
elif [ $RELEASE = "jaunty" ]; then
	VERSION_STRING="nc10"
else
	echo "The current ubuntu version is not supported by this script."
	exit 1
fi

# Get a list of all packages installed from voRia's repository
echo "* Getting a list of all packages installed from voRia's repository..."
PACKAGES=`dpkg -l | grep $VERSION_STRING | grep "^ii" | cut -d' ' -f 3`

# Make sure that 'xserver-xorg-video-all' package from official
# Ubuntu repositories will be reinstalled.
PACKAGES=`echo $PACKAGES "xserver-xorg-video-all"`

# Prepare packages to be downgraded
echo "* Selecting the best version to install for all the packages..."
REMOVE_PACKAGES="" # List of packages which dont have an official Ubuntu version
for PACKAGE in $PACKAGES; do
	# Search for the best version to install
	BEST_VERSION=`apt-cache show $PACKAGE | grep Version | cut -d' ' -f 2`
	BEST_VERSION="`echo $BEST_VERSION | cut -d' ' -f 2`"
	if echo $BEST_VERSION | grep $VERSION_STRING > /dev/null; then
		# Package has to be removed
		REMOVE_PACKAGES=`echo $REMOVE_PACKAGES $PACKAGE`
		PACKAGES=`echo $PACKAGES | sed "s|$PACKAGE||"`
	else
		# Set the best version in the PACKAGES list
		PACKAGES=`echo $PACKAGES | sed "s|$PACKAGE |$PACKAGE=$BEST_VERSION |"`
	fi
done

# Downgrade packages
echo "* Reinstalling official Ubuntu packages..."
apt-get install --reinstall $PACKAGES

# Remove all the remaining packages
echo "* Removing all the no more needed packages..."
apt-get purge --auto-remove $REMOVE_PACKAGES

echo "Done."

