#!/bin/sh

insert_keys()
{
# for now we do not use ximian key, but it is here, ready for deployment
KEYS_TXT=(MATHPU-GPG-KEY    )
SIGS_TXT=(b2980b13-3c1d0597 )
KEY_LOCATION=(/usr/share/doc/yum )
for i in `seq 0 $[ ${#KEYS_TXT[@]} - 1 ]`; do
 rpm -q gpg-pubkey-${SIGS_TXT[$i]} >/dev/null 2>&1 || rpm --import ${KEY_LOCATION[$i]}*/${KEYS_TXT[$i]}
done
}

OTHEROPTS=""
ONLYKEYS=""
while getopts "kyR:" Option
do
        case $Option in
                        k)
                                ONLYKEYS="TRUE"
                                ;;
			R)
				OTHEROPTS="-R $OPTARG"
				;;
			y)
				YUMONLY="true"
				;;
			*)
				echo $Option
				echo $OPTARG
				;;
        esac
done

if [ -n "$ONLYKEYS" ]; then
	echo "No autoupdate attempted, only adding rpm signing keys"
	insert_keys
else
	insert_keys
	# we do clean every night - only that way we can recover from errors :(
	/usr/bin/yum -e 0 -d 1 clean
	if [ -n "$YUMONLY" ]; then
		/usr/bin/yum $OTHEROPTS -e 0 -d 1 -y update yum
	else
		# First make sure /etc/gtk-2.0/i386-redhat-linux-gnu points to 
		# /etc/gtk-2.0/i686-redhat-linux-gnu
		if [ -d /etc/gtk-2.0/i686-redhat-linux-gnu -a ! -e /etc/gtk-2.0/i386-redhat-linux-gnu ]; then
			ln -s /etc/gtk-2.0/i686-redhat-linux-gnu /etc/gtk-2.0/i386-redhat-linux-gnu
		fi
		# an error during install due to various dependencies, this is the easiest
		# way to get it fixed - both 2.2.3-2.PU_IAS.2 and 2.2.3-6 are installed
		# so remove from db the old one
		if /bin/rpm -q librsvg2-2.2.3-2.PU_IAS.2 >/dev/null; then
			if [ `/bin/rpm -q librsvg2 | wc -l` -gt 1 ]; then
				rpm --justdb -e librsvg2-2.2.3-2.PU_IAS.2
			fi
		fi
		# We have to do an upgrade on certain packages, but only if they are there
		UPGRADE=""
		if /bin/rpm -q iscsi >/dev/null; then
			UPGRADE="$UPGRADE iscsi"
		fi
		if /bin/rpm -q mozilla-nspr >/dev/null; then
			UPGRADE="$UPGRADE mozilla*"
		fi
		if /bin/rpm -q ethereal >/dev/null; then
			UPGRADE="$UPGRADE ethereal*"
		fi
		if /bin/rpm -q gaim >/dev/null; then
			UPGRADE="$UPGRADE gaim"
		fi
		if [ -n "$UPGRADE" ]; then
			echo Attempting to do upgrades for $UPGRADE
			if [ -n "$OTHEROPTS" ]; then
				echo Sleeping a bit before doing the upgrade
				sleep $[ $RANDOM % 300 ]
			fi
			/usr/bin/yum -e 0 -d 1 -y upgrade $UPGRADE
		fi
		/usr/bin/yum $OTHEROPTS -e 0 -d 1 -y update
	fi
fi
