#!/bin/bash
#
# $Id: cdd-role 431 2006-10-23 06:11:32Z tille $

usage () {
   echo "Usage:  `basename $0` <action> <CDD> [<role>]"
   echo "action: add|del"
   echo "CDD:    `getCDDList|tr ' ' '|'`"
   echo "role:   `getCDDList|tr ' ' '|'` (default: CDD name)"
}


# the base dir for CDD conffiles, where script expects to find dirs named like
# each registered CDDs 
CONFBASE=${CONFBASE:-/etc/cdd}

# should be /usr/lib/cdd/*, file should be named differently
. ${CONFBASE}/cdd.conf


# Check consistency of passed argouments
if [ $# -eq 0 ]; then
   usage
   exit 67 # EX_USAGE
fi
if [ "`toLower $1`" != "add" -a "`toLower $1`" != "del" ] ; then
   echo "Missing or wrong action name."
   echo
   usage
   exit 67 # EX_USAGE
fi
if [ -z "$2" ] ; then
   echo "Missing CDD name."
   echo
   usage
   exit 67 # EX_USAGE
fi


ACTION=`toLower $1`
CDD=$2
ROLE=${3:-${CDD}}

# Now that we know the selected CDD, we can check if there is a local
# configuration for it (ie differnt backend from the default one)
test -n "${CDD}" -a  -f ${CONFBASE}/${CDD}/${CDD}.conf &&
	. ${CONFBASE}/${CDD}/${CDD}.conf


if [ -n "${DBBACKEND}" ]; then
	set -e
	checkCDD ${CDD} || cddFail $? "Custom Distribution ${CDD} does not exist"

	if [ "${ACTION}" = "add" ]; then
		checkCDD ${CDD} || cddFail $? "CDD ${CDD} does not exist"
		checkRole ${ROLE} && cddFail $? "Role ${ROLE} currently exist"
		checkRoleInCDD ${CDD} ${ROLE} || \
			cddFail $? "CDD (${CDD}) and Role (${ROLE}) are not correct or incompatible with the selected backend"

		addRole ${CDD} ${ROLE} || \
			cddFail $? "Failed to add role ${ROLE}"
	elif [ "${ACTION}" = "del" ]; then
		checkCDD ${CDD} || cddFail $? "CDD ${CDD} doesn't exist"
		checkRole ${ROLE} || cddFail $? "Role ${ROLE} doesn't exist"
		checkRoleInCDD ${CDD} ${ROLE} || \
			cddFail $? "CDD (${CDD} and Role (${ROLE}) are not correct"

		delRole ${CDD} ${ROLE} || \
			cddFail $? "Failed to remove role ${ROLE}"
		cddLog Role ${ROLE} successfully registered in CDD ${CDD}
	fi
	set +e

else
	# EX_USAGE
	cddFail 67 "You chose to not use Roles"
fi
