#!/bin/bash
#
# register.sh - Register a system with UIC's RHN Satellite server
#
# Maintainer: <MAINTAINER>
# Version: <VERSION>
# 
# This file is maintained in subversion as part of the <PROJNAME>
# application.

set -o errexit

#if ! [ -e /usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT ]; then
	wget -O /usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT http://rhnsat.cc.uic.edu/pub/RHN-ORG-TRUSTED-SSL-CERT
#fi

ACTIVATION_KEY=$1

/bin/rm -f /var/lib/rpm/__db*
/bin/rpm --rebuilddb

if [ -e /tmp/rhnreg.post ]; then
	rm /tmp/rhnreg.post
fi

if ! rpm -q gpg-pubkey-db42a60e; then
	if [ -e /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-former ]; then
		rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-former || true
	elif [ -e /usr/share/rhn/RPM-GPG-KEY ]; then
		rpm --import /usr/share/rhn/RPM-GPG-KEY || true
	fi
fi

if ! ( rpm -q gpg-pubkey-fd431d51 || rpm -q gpg-pubkey-37017186 ); then
	if [ -e /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release ]; then
		rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release || true
	fi
fi

if ! rpm -q gpg-pubkey-1f60f7e2; then
	if [ -d /etc/pki/rpm-gpg ]; then
		DIR=/etc/pki/rpm-gpg
	else
		DIR=/usr/share/rhn
	fi
	wget -O $DIR/RPM-GPG-KEY-UIC-ACCC http://rhnsat.cc.uic.edu/pub/RPM-GPG-KEY-UIC-ACCC
	rpm --import $DIR/RPM-GPG-KEY-UIC-ACCC || true
fi

sed -i.bak \
	-e 's/xmlrpc.rhn.redhat.com/rhnsat.cc.uic.edu/g' \
	-e 's/rhn.cc.uic.edu/rhnsat.cc.uic.edu/g' \
	-e 's/RHNS-CA-CERT/RHN-ORG-TRUSTED-SSL-CERT/g' \
	/etc/sysconfig/rhn/up2date

if ! fgrep 'NetworkSetup=' /etc/sysconfig/rhn/up2date >/dev/null 2>&1
then
	cat <<EOF >>/etc/sysconfig/rhn/up2date

NetworkSetup[comment]=None
NetworkSetup=1
EOF
else
	sed -i -e 's/NetworkSetup=.*/NetworkSetup=1/' /etc/sysconfig/rhn/up2date
fi

PROFILENAME_OPT=''
if [ -n "$PROFILENAME" ]
then
	PROFILENAME_OPT="--profilename=$PROFILENAME"
fi

if [ -n "$ACTIVATION_KEY" ]
then
	rhnreg_ks --force --nohardware "--activationkey=$ACTIVATION_KEY" "$PROFILENAME_OPT"
else
	rhn_register
fi

if [ -x /tmp/rhnreg.post ]; then
	/tmp/rhnreg.post
fi
