#       @(#)selectdevice        1.2     /sccs/src/cmd/sadmin/shell/s.selectdevice
#       Select one of the simple administration names for a block or character
#       device.

#!      chmod +x ${file}

pid=${2:?}
case "$1" in
-b )    #       block device
       type=-b
       typename=block
       r=
       ;;
-c )    #       character (aka raw) device
       type=-c
       typename=character
       r=r
       ;;
* )
       echo >&2 "Usage:  $0 -[b|c] pid [dir [names ...]]"
       exit 1
esac

if [ $# -lt 3 ]
then
       #default directory to /dev/${r}SA
       set -- $1 $2 /dev/${r}SA
fi
DIR=$3

if [ ! -d $DIR ]
then
       admerr $0 $DIR nonexistent directory
       exit 1
fi

rm -f /usr/tmp/$$.list
cd $DIR
shift 3
if [ $# -eq 0 ]
then
       # default to everything in directory
       ls >/usr/tmp/$$.list
else
       for DEVTYPES in $*
       do
               ls | grep "${DEVTYPES}[0-9][0-9]*" >>/usr/tmp/$$.list
       done
fi
if [ ! -s /usr/tmp/$$.list ]
then
       admerr $0 Problems in $DIR, no valid ${typename} devices.
       rm -f /usr/tmp/$$.list
       exit 1
fi

set -- `cat /usr/tmp/$$.list`

if [ $# = 1 ]
then
       if [ ! ${type} "$1" ]
       then
               admerr $0 $1 is not of type ${typename}
               rm -f /usr/tmp/$$.list
               exit 1
       fi

       echo $DIR/$1
       rm -f /usr/tmp/$$.list
       exit 0
elif [ $# -gt 1 ]
then
       list=`pr -tn /usr/tmp/$$.list`
       select=`checklist -k "${pid}" -fep -H "
The menu items indicate possible devices for use by this subcommand.
Your selection will determine the particular device to be used." "
Select which device to use:

${list}

Enter a number, a name, the initial part of a name, or
? for HELP, q to QUIT:" ${list} q`
       case ${select} in
       q )
               rm -f /usr/tmp/$$.list
               exit 0 ;;
       [1-9] | [1-9][0-9]* )
               shift `expr $select - 1`
               DEV=$DIR/$1
               ;;
       * )
               DEV=$DIR/${select}
       esac
       if [ ! ${type} $DEV ]
       then
               admerr $0 $DEV is not of type ${typename}
               rm -f /usr/tmp/$$.list
               exit 1
       fi
       echo $DEV
       rm -f /usr/tmp/$$.list
       exit 0
fi