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

usage() {
   echo "Usage: `basename $0` [ -u <user> | -d <CDD> ]"
   echo "CDD:   `getCDDList|tr ' ' '|'`"
   echo "user:  system user registerd to a CDD"
   echo
   echo "run as user updates only the user's menu script"
}

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

# a local per CDD conf is sourced later, after argument parsing
. ${CONFBASE}/cdd.conf

# specific utilities for cdd-update-menus
. ${SHAREDIR}/cdd-update-menus

# Get command line arguments
GETOPT=`getopt -o d:u:h --long cdd:,user:,help -n "$0" -- "$@"`
eval set -- "$GETOPT"
while true
do
	case $1 in
		-h|--help)
            usage
            exit 0
            ;;
		# get distro name
		-d|--cdd)
			if ! amI root; then
				cddLog "You must be root to specify --cdd parameter"
				cddLog ""
				usage
				exit 64
			elif [ -n "${CDDUSER}" ]; then
				cddLog "You cannot specify --cdd and --user at the same time" 
				cddLog ""
				usage
				exit 0
			else
				CDD=$2
				shift 2
			fi
			;;
		# get user name
		-u|--user)
			CDDUSER=$2
			shift 2

			if ! amI root && ! amI "${CDDUSER}"; then
				cddLog  "You must be root to specify --user parameter with a user that's not you"
				usage
				exit 64
			elif [ "${CDDUSER}" == 'root' ]; then
				cddFail 64 "err: Menus for user 'root' cannot be updated"
			elif [ -n "${CDD}" ]; then
				usage
				exit 0
			fi
			;;
		--)
			shift
			break
			;;
		*)
			cddLog "$1 not recognized as option" >&2
			exit 67 # EX_USAGE
			;;
	esac
done


# update menu scripts for CDDUSER, for any CDD, if any
if [ -n "${CDDUSER}" ]; then 
	SYSSCRIPT="${SHAREDIR}/menu/cdd-menu"
	USERSCRIPT="`getUserHome ${CDDUSER}`/.menu/cdd-menu"

	set -e
	checkUser ${CDDUSER} || \
		cddFail 67 "User does not exist"
	isUserRegistered ${CDDUSER} || \
		cddFail 67 "User ${CDDUSER} is not registered to any CDD"
	
	# there's nothing to do on per user basis criteria
	#updateUser ${CDDUSER} "${SYSSCRIPT}" "${USERSCRIPT}"
	set +e

# update menu scripts for any user registered into the specified CDD
elif [ -n "${CDD}" ]; then 
	# 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
		
	set -e
	checkCDD ${CDD} || \
		cddFail $? "Custom distribution ${CDD} does not exist"
		
	# there's nothing to do on per CDD basis criteria
	#SYSSCRIPT="${SHAREDIR}/menu/cdd-menu"
	#updateCDD ${CDD} "${SYSSCRIPT}"
	set +e
else
    exec $0 --user `whoami`
fi 
