#!/bin/bash
#
# check_packages.sh version 0.2
# written by John Newbigin <jn@it.swin.edu.au>
#
# This script is designed to help complete a live upgrade to
# CentOS-2.  It is not well tested or designed to be robust
# make sure you read the output carefully before running it
final=centos2-final-package-list
if [ ! -f $final ] ; then
   echo "Can't find $final, trying to download it"
   wget http://uranus.it.swin.edu.au/~jn/linux/centos-2/$final
   if [ ! -f $final ] ; then
      echo "Try downloading it from http://uranus.it.swin.edu.au/~jn/linux/centos-2/$final"
      exit 1
   fi
fi

# John's INI file reader
#####################
section=""
for i in `cat /etc/yum.conf` ; do
  if [ "$i" ] ; then
    if (echo $i | grep -q "\\[.*]") ; then
      section=`echo $i | cut -d "" -f 1| tr -d "[" | tr -d "]" `
      #echo Start Section [$section]
    else
      if [ "$section" = "base" ] ; then
        key=`echo $i | cut -d "=" -f 1`
        value=`echo $i | cut -d "=" -f 2`
        #echo "$key=$value"
        # clean up the section
        section=`echo $section | tr - _`
        export ${section}_${key}=${value}
      fi
    fi
  fi

done
#####################

URL=http://mirror.centos.org/centos-2/final/i386/CentOS/RPMS/
if [ "$base_baseurl" ] ; then
   URL=$base_baseurl../../final/i386/CentOS/RPMS/
fi

# the guts of the script
combine=""
TMPFILE=`mktemp /tmp/$0.XXXXXX` || exit 1
rpm -qa | sort >> $TMPFILE
for i in `cat $TMPFILE` ; do
   vendor=`rpm -q $i --queryformat "%{vendor}"`
   if [ "$vendor" != "CentOS" ] ; then
      if grep -q $i $final ; then
         echo $i Version match OK > /dev/null
      else
         name=`rpm -q $i --queryformat "%{name}"`
	 if [ "$name" = "kernel" ] ; then
	    echo "# Skipping $i"
         elif grep -q "^$name " $final ; then
            echo "# Need to downgrade $name"
	    if [ "$1" = "--combine" ] ; then
	       file=`grep "^$name " $final | awk '{print $3}' | tail -1`
	       combine="$combine $file"
	    else
               echo -n "rpm --oldpackage -U $URL"
               grep "^$name " $final | awk '{print $3}'
            fi
         else
            echo "# $name ($vendor) is not part of CentOS"
         fi
      fi
   fi
done
if [ "$combine" ] ; then
   echo -n "rpm --oldpackage -U"
   for i in $combine ; do 
      echo " \\"
      echo -n " $URL$i"
   done
   echo
fi
rm $TMPFILE

