#!/bin/bash
echo Steadfast Spacewalk Setup running....
echo =====================================
echo

id | egrep "^uid=0" > /dev/null
if [ $? -ne 0 ] ; then
  echo ERROR: Script must be run as user root
  echo Run $0 as root
  exit 1
fi

if [ ! -f /etc/redhat-release ] ; then
  echo ERROR: Not a CentOS system
  exit 1
fi

egrep "^CentOS " /etc/redhat-release > /dev/null
if [ $? -ne 0 ] ; then
  echo ERROR: Not a CentOS system
  exit 1
fi

echo
echo Installing Spacewalk Client ...
echo -------------------------------
echo
yum -y \
  --enablerepo=steadfast-mirror-centos-base \
  --enablerepo=steadfast-mirror-centos-updates \
  --enablerepo=steadfast-mirror-epel \
  --enablerepo=steadfast-spacewalk-client \
  install spacewalk-client-repo rhn-setup yum-rhn-plugin python-dmidecode \
    rhncfg rhncfg-actions rhncfg-client osad python-hashlib
if [ $? -ne 0 ] ; then
  echo ERROR: Could not install spacewalk client RPMs
  echo Correct the problem and run $0 again
  exit 1
fi

echo
echo Configuring Spacewalk Client ...
echo --------------------------------
echo
cd /usr/share/rhn/
wget -O RHN-ORG-TRUSTED-SSL-CERT \
  http://spacewalk.steadfast.net/pub/RHN-ORG-TRUSTED-SSL-CERT
sed -i \
 's#osa_ssl_cert = .*#osa_ssl_cert = /usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT#' \
  /etc/sysconfig/rhn/osad.conf
if [ -f /sbin/chkconfig ] ; then
  /sbin/chkconfig osad on
elif [ -f /usr/sbin/chkconfig ] ; then
  /usr/sbin/chkconfig osad on
fi

echo
echo Enable privileged RHN actions ...
echo ---------------------------------
echo

/usr/bin/rhn-actions-control --enable-deploy --enable-diff

echo
echo Registering Spacewalk Client ...
echo --------------------------------
echo
ARCH=`uname -i`
if [ $ARCH != "x86_64" ] ; then
  ARCH="i386"
fi
CENTOSVER=`sed 's/^[^0-9]*//;s/[^0-9].*//' /etc/redhat-release`
/usr/sbin/rhnreg_ks -v --serverUrl=http://spacewalk.steadfast.net/XMLRPC \
  --activationkey=1-centos${CENTOSVER}-${ARCH}

echo
echo Starting Spacewalk OSA service ...
echo ----------------------------------
echo
if [ -f /sbin/service ] ; then
  /sbin/service osad start
elif [ -f /usr/sbin/service ] ; then
  /usr/sbin/service osad start
fi

echo
echo Checking YUM configuration ...
echo ------------------------------
echo

egrep "^plugins *= *1$" /etc/yum.conf > /dev/null
if [ $? -eq 0 ] ; then
  echo YUM plugins are already enabled
fi

egrep "^plugins *= *0$" /etc/yum.conf > /dev/null
if [ $? -eq 0 ] ; then
  echo YUM plugins disabled, re-enabling them
  sed -i 's/^plugins *= *0$/plugins=1/' /etc/yum.conf
fi

egrep "^plugins *=" /etc/yum.conf > /dev/null
if [ $? -ne 0 ] ; then
  echo YUM plugins option missing
  sed -i 's/^\[main\]$/&\nplugins=1/' /etc/yum.conf
  egrep "^plugins=1$" /etc/yum.conf > /dev/null
  if [ $? -eq 0 ] ; then
    echo Configuration corrected to include YUM plugins option
  else
    echo The YUM "[main]" section not correctly found
    echo Please correct the /etc/yum.conf manually
  fi
fi

echo
echo Setup completed
echo ===============
echo

