#! /bin/bash
check_error() { if test $1 != 0; then echo $2; exit $1; fi }
DEBUGINFOREPO="rhel-debuginfo"

if [ "$#" -lt 1 ]; then
    UNAME=`uname -r` # determine current kernel on local machine
else
    UNAME=$1 #user passed in value
fi
UNAME=`echo $UNAME | sed "s/ //"`
KERNEL="kernel"
for VARIANT in debug kdump PAE xen; do
  TMP=`echo $UNAME | sed s/$VARIANT//`
  if [ "$TMP" != "$UNAME" ]; then
      UNAME=$TMP; KERNEL="kernel-$VARIANT"
  fi
done
DIR=`mktemp -d` || exit 1
pushd $DIR
KERN_ARCH=$(uname -m)
#KERN_REV value from target "uname -r" minus the arch
KERN_REV=`echo $UNAME | sed s/.$KERN_ARCH//`
CANDIDATES="$KERNEL-$KERN_REV $KERNEL-devel-$KERN_REV \
$KERNEL-debuginfo-$KERN_REV kernel-debuginfo-common-$KERN_REV"
NEEDED=`rpm -q $CANDIDATES|grep "is not installed" | awk '{print $2}'`
if [ "$NEEDED" != "" ]; then
    yumdownloader --enablerepo=$DEBUGINFOREPO $NEEDED
    check_error $? "problem downloading rpm(s) $NEEDED"
    rpm --force -ivh *.rpm
    check_error $? "problem installing rpm(s) $NEEDED"
fi
popd
#cleanup
rm -r $DIR
