#! /usr/bin/ksh
#
#       @(#)u4ftdev_select	1.3	98/06/04
#
#   List on stdout that subset of devinfo cookie(s) having matching
#   values for the specified attributes ...
#
#   Arg1 can be a single cookie; a literal "*", meaning ALL cookies
#   or "-", in which case a list of cookies is read from stdin, one
#   per line (extra words after the first on each line will be ignored)
#
#   Each subsequent argument can specify a primitive attribute of
#   a devinfo node (e.g. state) or a datatype and property name,
#   followed by a match-operator "~" or "!~" and a pattern that the
#   attribute must match (or not match, if "!~" was used).  Note
#   that invalid attributes and non-existent properties are treated
#   as having null values rather than producing an error.
#

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

usage()
{
    exec >&2
    echo "Usage: ${0##*/} [cookie|*|-] [attribute|type:name][!]~pattern ..."
    exit 1
}

case $# in
0|1)
    usage
    ;;
*)
    cookie="$1"
    shift
    ;;
esac

set -A arg
set -A enq
set -A mat
set -A pat

for attr
do
    tmp="${attr}"
    pat[${#pat[@]}]="${attr#*~}"
    attr="${attr%%~*}"
    case "$attr" in
    "$tmp")
        usage
        ;;
    *!)
        mat[${#mat[@]}]="1"
        attr="${attr%?}"
        ;;
    *)
        mat[${#mat[@]}]="0"
        ;;
    esac
    case "$attr" in
    *:*)
        enq[${#enq[@]}]="prop_find_${attr%%:*}s"
        arg[${#arg[@]}]="${attr#*:}"
        ;;
    *)
        enq[${#enq[@]}]="get_${attr%%:*}"
        arg[${#arg[@]}]=""
        ;;
    esac
done

case "$cookie" in
-)
    cat
    ;;
"*")
    u4ftctl find /
    ;;
*)
    echo "$cookie"
    ;;
esac |
while read cookie junk
do
    let i=${#enq[@]}
    while (( (i -= 1) >= 0 ))
    do
        val=$(u4ftctl "${enq[$i]}" "$cookie" ${arg[$i]:+"${arg[$i]}"}) ||
        val=""
        [[ "$val" == ${pat[$i]} ]]
        [[ $? -ne ${mat[$i]} ]] && break
    done 2> /dev/null
    (( i < 0 )) && echo "$cookie"
done

