#!/bin/false # This is a ksh script library, to be sourced by utconfig, etc.
#
# ident "@(#)config_lib.ksh	1.1 07/03/19 SMI"
#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
## Helper functions for input validation
#

# An alphanumeric identifier (C-style) of up to 24 characters
IsValidAlphanumeric()
{
   (($# == 1 && ${#1} <= 24)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   [[ $param == [a-zA-Z0-9]+([_a-zA-Z0-9-]) && $1 != *- ]]
}

# A valid positive integer (no sign includede)
IsValidInteger()
{
   (($# == 1 && ${#1} <= 24)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   [[ $param == +([0-9]) ]]
}

# A valid unix group name on both Linux and Solaris
IsValidGroup()
{
   (($# == 1)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   #
   ## Rules/restrictions for group names on Solaris and Linux differ.
   ## The following is a lowest common denominator compromise
   #
   [[ $param == [a-z]*([a-z0-9]) ]]
}


#
## GroupExists
#
## Checks whether a name designates an existing unix group
#
GroupExists()
{
   (($# == 1)) || return 1

   getent group "$1" > /dev/null 2>&1 
}

#
## ReplyIsYes / ReplyIsNo
## XXX: temporarily named ReplyIsYes_ / ReplyIsNo_
#
## Interaction helpers: get a yes/no response
#
## ReplyIsYes: default reply = yes; returns 0 for y[es] reply, 1 for n[o] 
## ReplyIsNo:  default reply = no;  returns 0 for n[0] reply, 1 for y[es] 
#
## The functions assume that a global variable $LOGFILE points to a logfile
## and log responses there.
#

# XXX: These functions also exist in the sras_config script, which is still 
# used by utconfig. To avoid name clashes, we use a modified name for now.
# TODO: Consolidate use of these functions by kiosk_config and srwa_config,
# when srwa_config moves to srcs and sras_config goes away.

# Defaults to Yes
ReplyIsYes_() {
  while true; do
    print -n "$* ([y]/n)? "
    read
    case "$REPLY" in
      "" | [yY] | [Yy][Ee][Ss])
        echo "Yes" >> $LOGFILE
        return 0;;
      [nN] | [Nn][Oo])
        echo "No" >> $LOGFILE
        return 1;;
      *)
        echo $REPLY >> $LOGFILE
    esac
  done
}

# Defaults to No
ReplyIsNo_() {
  while true; do
    print -n "$* (y/[n])? "
    read
    case "$REPLY" in
      "" | [nN] | [Nn][Oo])
        echo "No" >> $LOGFILE
        return 0;;
      [yY] | [Yy][Ee][Ss])
        echo "Yes" >> $LOGFILE
        return 1;;
      *)
        echo $REPLY >> $LOGFILE
    esac
  done
}

