#!/bin/bash
# CreateRHELPulpRepos.sh
# Peforms each of the following steps if necessary for each of the listed repo-ids and source paths:
# 1) Creates the RHEL repositories in pulp
# 2) Configures a synchronisation timetable.
#
# NOTE: pulp-admin must be logged in before running this script:
# pulp-admin login -u admin -p admin
# https://pulp-user-guide.readthedocs.org/en/latest/admin-client/authentication.html
# 
# NOTE: This script must be run as root to access the system certificates and entitlements.
#
# NOTE: An appropriate entitlement certificate is required to access each 
# operating system series {client|workstation|server}.

# The cert_number can be found in the directory /etc/pki/entitlement
# after you have run Red Hat Subscription Manager and configured a subscription.
# Put JUST THE NUMBER of the .pem and -key.pem files here.
cert_number=

if [ -z "${cert_number}" ]
then
	echo "$0: Need to set cert_number in the script." >2
	exit 1
fi

#set -x

# Update once a week, over the weekend.
#http://en.wikipedia.org/wiki/ISO_8601#Repeating_intervals
SYNC_PERIOD="2014-11-28T20:10+10:00/P1W"

function ConfigureRPMRepo() {
	local REPO_ID=$1
	local URL=$2
	local RELATIVE_URL=$3

	echo Configuring $REPO_ID

	# Does the repo exist already?
	if ! pulp-admin rpm repo update --repo-id=${REPO_ID} >&/dev/null
	then
		# doesn't exist yet
		pulp-admin rpm repo create --repo-id=${REPO_ID} || return 1
	fi
	pulp-admin rpm repo update \
		--repo-id=${REPO_ID} \
		--feed=${URL} \
		${KEY_ARGS} \
		--validate true \
		--relative-url=${RELATIVE_URL} \
		--serve-http true || return 1

	# Sync it
	#pulp-admin rpm repo sync run --repo-id=${REPO_ID} || return 1

	# Schedule periodic updates
	RemoveSyncSchedulesFromRepo	rpm ${REPO_ID}
	pulp-admin rpm repo sync schedules create -s "${SYNC_PERIOD}" --repo-id=${REPO_ID} || return 1

	echo Completed $REPO_ID
}

function SyncAllRepos() {
	local RepoTypes="rpm iso"
	local RepoType
	for RepoType in $RepoTypes
	do
		local AllRepoNames=( $(pulp-admin $RepoType repo list --fields=Id | sed --quiet -e "s/Id: \+\([^ \t]\+\)/\1/p") )
		local i
		for (( i=0; i<${#AllRepoNames[@]}; ++i ))
		do
			pulp-admin $RepoType repo sync run --repo-id=${AllRepoNames[i]}
		done
	done
}

function CancelAllTasks() {
	local AllTaskIds=( $(pulp-admin tasks list | sed --quiet -e "s/Task Id: \+\([^ \t]\+\)\$/\1/p") )
	local i
	for ((i=0; i<${#AllTaskIds[@]}; ++i ))
	do
		pulp-admin tasks cancel --task-id ${AllTaskIds[i]}
	done
}

function CancelAllRunningTasks() {
	local AllTaskIds=( $(pulp-admin tasks list | perl -0777 -pe 's/Operations:[^\n]*\nResources:[^\n]*\nState: +(Running|Waiting)\nStart Time: +[^ \n]+\nFinish Time: +[^ \n]+\nTask Id: +([^ \n]+)/\2/igs' | grep -e "^[a-f0-9\-]\+\$") )
	local i
	for ((i=0; i<${#AllTaskIds[@]}; ++i ))
	do
		pulp-admin tasks cancel --task-id ${AllTaskIds[i]}
	done
}

function DeleteAllRepos() {
	local RepoTypes="rpm iso"
	local RepoType
	for RepoType in $RepoTypes
	do
		local AllRepoNames=( $(pulp-admin $RepoType repo list --fields=Id | sed --quiet -e "s/Id: \+\([^ \t]\+\)/\1/p") )
		local i
		for (( i=0; i<${#AllRepoNames[@]}; ++i ))
		do
			pulp-admin $RepoType repo delete --repo-id=${AllRepoNames[i]}
		done
	done
}

function RemoveSyncSchedulesFromRepo() {
	local RepoType=$1
	local RepoId=$2
	local SCHEDULES=( $( pulp-admin $RepoType repo sync schedules list --repo-id=${RepoId} | sed --quiet -e "s/Id: \+\([^ \t]\+\)/\1/p") )
	local j
	for (( j=0; j<${#SCHEDULES[@]}; ++j ))
	do
		pulp-admin $RepoType repo sync schedules delete --repo-id=${RepoId} --schedule-id=${SCHEDULES[j]}
	done
}

function RemoveAllSyncSchedules() {
	local RepoTypes="rpm iso"
	local RepoType
	for RepoType in $RepoTypes
	do
		local AllRepoNames=( $(pulp-admin $RepoType repo list --fields=Id | sed --quiet -e "s/Id: \+\([^ \t]\+\)/\1/p") )
		local i
		for (( i=0; i<${#AllRepoNames[@]}; ++i ))
		do
			RemoveSyncSchedulesFromRepo ${RepoType} ${AllRepoNames[i]}
		done
	done
}

function ConfigureRedHatWorkstationRepos() {
	local BASE_URL=https://cdn.redhat.com/content/dist/rhel

	# The location can be found by running subscription-manager-gui
	# It can be found in the menus at System Tools | Red Hat Subscription Manager
	# Then choose System | Repositories from the application menu.
	# This will provide a list of repositories (available for the installed operating system),
	# and show the Base URL for the selected repository.

	# locations can be checked using the following command:
	# curl -v --proxy http://$user:$password@$proxy_server:$proxy_port/ https://cdn.redhat.com/content/dist/rhel/workstation/6/6Workstation/x86_64/debug --insecure --cert /etc/pki/entitlement/$cert_number.pem --key /etc/pki/entitlement/$cert_number-key.pem


	# These keys are for workstation.
	# These keys were obtained by using a license. The files were written by the subscription manager.
	KEY_ARGS="--feed-ca-cert=/etc/rhsm/ca/redhat-uep.pem --feed-cert=/etc/pki/entitlement/${cert_number}.pem --feed-key=/etc/pki/entitlement/${cert_number}-key.pem"

	local Items=(
		rhel-5-workstation-x86_64		workstation/5/5Client/x86_64
		rhel-5.7-workstation-x86_64		workstation/5/5.7/x86_64
		rhel-5.8-workstation-x86_64		workstation/5/5.8/x86_64
		rhel-5.9-workstation-x86_64		workstation/5/5.9/x86_64
		rhel-5.10-workstation-x86_64	workstation/5/5.10/x86_64
		rhel-5.11-workstation-x86_64	workstation/5/5.11/x86_64
	
		rhel-5-workstation-i386			workstation/5/5Client/i386
		rhel-5.7-workstation-i386		workstation/5/5.7/i386
		rhel-5.8-workstation-i386		workstation/5/5.8/i386
		rhel-5.9-workstation-i386		workstation/5/5.9/i386
		rhel-5.10-workstation-i386		workstation/5/5.10/i386
		rhel-5.11-workstation-i386		workstation/5/5.11/i386

		rhel-6-workstation-x86_64		workstation/6/6Workstation/x86_64
		rhel-6.0-workstation-x86_64		workstation/6/6.0/x86_64
		rhel-6.1-workstation-x86_64		workstation/6/6.1/x86_64	
		rhel-6.2-workstation-x86_64		workstation/6/6.2/x86_64
		rhel-6.3-workstation-x86_64		workstation/6/6.3/x86_64
		rhel-6.4-workstation-x86_64		workstation/6/6.4/x86_64
		rhel-6.5-workstation-x86_64		workstation/6/6.5/x86_64
		rhel-6.6-workstation-x86_64		workstation/6/6.6/x86_64
		rhel-6.7-workstation-x86_64		workstation/6/6.7/x86_64
	
		rhel-6-workstation-i386			workstation/6/6Workstation/i386
		rhel-6.0-workstation-i386		workstation/6/6.0/i386
		rhel-6.1-workstation-i386		workstation/6/6.1/i386
		rhel-6.2-workstation-i386		workstation/6/6.2/i386
		rhel-6.3-workstation-i386		workstation/6/6.3/i386
		rhel-6.4-workstation-i386		workstation/6/6.4/i386
		rhel-6.5-workstation-i386		workstation/6/6.5/i386
		rhel-6.6-workstation-i386		workstation/6/6.6/i386
		rhel-6.7-workstation-i386		workstation/6/6.7/i386

		rhel-7-workstation-x86_64		workstation/7/7Workstation/x86_64
		rhel-7.0-workstation-x86_64		workstation/7/7.0/x86_64
		rhel-7.1-workstation-x86_64		workstation/7/7.1/x86_64
	)

	local NUM_COLS=2
	local NUM_REPOS=$((${#Items[@]}/${NUM_COLS}))
	local i

	for (( i==0; i<NUM_REPOS; ++i ))
	do
		REPO_ID=${Items[i*NUM_COLS+0]}
		REPO_PATH=${Items[i*NUM_COLS+1]}
		URL=${BASE_URL}/${REPO_PATH}
		MAJOR=$(echo ${REPO_PATH} | sed --quiet -e "s#^[^/]\+/\([^/]\+\)/.*\$#\1#p")
	
		ConfigureRPMRepo ${REPO_ID} 						${URL}/os							rhel/${REPO_PATH}/os							|| return 1
		ConfigureRPMRepo ${REPO_ID}-source					${URL}/source/SRPMS					rhel/${REPO_PATH}/source/SRPMS					|| return 1
		ConfigureRPMRepo ${REPO_ID}-debug					${URL}/debug						rhel/${REPO_PATH}/debug							|| return 1
		if (( MAJOR >= 6 )); then
		# optional doesn't exist for RHEL < 6.
		ConfigureRPMRepo ${REPO_ID}-optional				${URL}/optional/os					rhel/${REPO_PATH}/optional/os					|| return 1
		ConfigureRPMRepo ${REPO_ID}-optional-source			${URL}/optional/source/SRPMS		rhel/${REPO_PATH}/optional/source/SRPMS			|| return 1
		ConfigureRPMRepo ${REPO_ID}-optional-debug			${URL}/optional/debug				rhel/${REPO_PATH}/optional/debug				|| return 1
		fi
		ConfigureRPMRepo ${REPO_ID}-supplementary			${URL}/supplementary/os				rhel/${REPO_PATH}/supplementary/os				|| return 1
		ConfigureRPMRepo ${REPO_ID}-supplementary-source	${URL}/supplementary/source/SRPMS	rhel/${REPO_PATH}/supplementary/source/	SRPMS	|| return 1
		ConfigureRPMRepo ${REPO_ID}-supplementary-debug		${URL}/supplementary/debug			rhel/${REPO_PATH}/supplementary/debug			|| return 1

		# This is not yet figured out.
		#ConfigureISORepo ${REPO_ID}-iso						${URL}/iso 		|| return 1
	done

	ConfigureRPMRepo rhel-6-workstation-x86_64-extras		${BASE_URL}/workstation/6/6Workstation/x86_64/extras/os		rhel/workstation/6/6Workstation/x86_64/extras/os	|| return 1
	ConfigureRPMRepo rhel-6-workstation-i386-extras			${BASE_URL}/workstation/6/6Workstation/i386/extras/os		rhel/workstation/6/6Workstation/i386/extras/os		|| return 1
	ConfigureRPMRepo rhel-7-workstation-x86_64-extras		${BASE_URL}/workstation/7/7Workstation/x86_64/extras/os		rhel/workstation/7/7Workstation/x86_64/extras/os	|| return 1
}

