#! /usr/bin/ksh
#
#       @(#)cmsTagDevice	1.2	99/06/07
#
#   Script to tag an existing devinfo node with its CMS id
#
#   The supplied <selectors> must be sufficient to uniquely identify
#   ONE devinfo.
#

export PATH=${CMSHOME:+"$CMSHOME/lib:"}$PATH

PROGM="u4ftdev_enq -m "
PROGS="u4ftdev_enq -s "
PROGT="u4ftdev_enq -t "

usage()
{
    echo "Usage: ${0##*/} <tag> <selector> ..." >&2
    exit 1
}

error()
{
    echo "${0##*/}: $@" >&2
    exit 2
}

if [[ $# -lt 2 ]]
then
    usage
fi

# PROGT will validate the tag, search for the cookie and set the tag
# in one shot. If the environmeent variables PTAG and DNAME corresponding
# to the tag of the parent device and the name of the device being tagged,
# respectively, are set then PROGT will attempt to optimise away the
# the need to search the platform configuration database (u4ftloc.data).
# It is undetermined whether this increases the performance of device
# tagging.

if [[ -n "$PROGT" ]]; then
	$PROGT "$@"
	exit "$?"
fi

#
#   Validate the <tag>
#
tag="$1"
shift
case "$tag" in
\(\))
    # default tag, always permitted
    ;;
\(*([!\)])\))
    # non-default tag - must not already be in use for another node
    set -A tagnodes $(u4ftctl find / "$tag")
    if [[ ${#tagnodes[@]} -gt 1 ]]
    then
        error "tag already in use"
    fi
    ;;
*)
    error "invalid tag"
    ;;
esac

#
#   Look up the devinfo using the selectors supplied,
#   and check that exactly ONE devinfo is found
#
set -A mynode $($PROGM "$@")
if [[ ${#mynode[@]} -gt 1 ]]
then
    error "more than one matching node!"
elif [[ ${#mynode[@]} -eq 0 ]]
then
    error "no matching node found"
elif [[ -n "$tagnodes" && "$tagnodes" != "$mynode" ]]
then
    error "tag already in use"
fi

u4ftctl set_tag "$mynode" "$tag"

