#!/bin/ksh
#
# ident "uttscadm.ksh $Date: 2011-04-08 14:38:10 -0700 (Fri, 08 Apr 2011) $ $Revision: 12881 $ Oracle"
#
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
#

# Admin CLI used for configuring the Sun Ray Connector

#
# Solaris 10 Trusted Extension guard
#

SUNWUTTSC_LOC=/opt/SUNWuttsc
SUNWUTTSCLIB=$SUNWUTTSC_LOC/lib

#
# Solaris 10 Trusted Extension guard 
#

TXGUARD=$SUNWUTTSCLIB/txguard
. $TXGUARD

PATH="/usr/sbin:/usr/bin:/sbin:/bin"
PROGRAM_ID=$(basename $0)
TMP_ADM_FILE="/var/opt/SUNWut/tmp/$PROGRAM_ID.$$.tmp"
PW_PID=
TMP_DIR_PATH="/var/run"
TMP_PROGID=${TMP_DIR_PATH}/$PROGRAM_ID.$$
TMP_PWPIPE="${TMP_PROGID}.pipe"

trap "rm -f $TMP_PWPIPE; stty echo </dev/tty; CleanupPipeProcs; exit 1"\
 HUP INT QUIT TERM

SUNWUTETC=/etc/opt/SUNWut
SUNWUTTSCETC=/etc/opt/SUNWuttsc
SUNWUTTSCETCLIB=$SUNWUTTSCETC/lib
UTADMIN_CONF=$SUNWUTETC/utadmin.conf
UTADMIN_PW=$SUNWUTETC/utadmin.pw
THIS_HOST=$(uname -n)
SRDS_LDAP_DEFAULT="${SUNWUTETC}/srds/default"
SRDS_LDAP_CURRENT="${SUNWUTETC}/srds/current"
UTDSD_CMD=/etc/init.d/utds
SRSS_PKG_LOC=/opt/SUNWut
SRSS_DYNAMIC_ADMIN=$SRSS_PKG_LOC/lib/libutadmin.so.1
SUNWUTLIB=$SRSS_PKG_LOC/lib
SUNWUTSBIN=$SRSS_PKG_LOC/sbin

SUNWUTPROTO=$SUNWUTTSCLIB/prototype
UTTSCPRINTERADM=$SUNWUTTSC_LOC/sbin/uttscprinteradm

. $SUNWUTETC/basedir/lib/support_lib/config_lib

ADMINSUBTREE=""
ADMINUSERNAME=""

RETCODE=0
ROOTPW=""

ETCSERVICES="/etc/services"
START_DELIMITER="#START SUNWuttsc"
END_DELIMITER="#END SUNWuttsc"
UTTSCPD="uttscpd"
UTTSCPDPORT="7014/tcp"
TMPFILE="/tmp/tmpservice.$$"
SRWC_GOPTS=""
SRWC_GROUP=""
SRWC_GROUP_OK=false
SRWC_GID=""
SRWC_GID_OK=false
OS=`/bin/uname -s`

function setAdminVars {

ADMINSUBTREE=`grep admin.subtree $UTADMIN_CONF | awk '{print $NF}'`
ADMINUSERNAME=`grep admin.user.name $UTADMIN_CONF | awk '{print $NF}'`
}

function mustBeRoot {
	case "$(id)" in
	'uid=0('*)
		;; 
	*)
		print -u2 "Must be root to configure/unconfigure Sun Ray Connector for Windows Operating Systems"
		exit 1
		;;
	esac
}

#
# Usage - prints the usage message
# $1 - the exit code
function Usage {

    cat <<!

Usage:
uttscadm -c -g <group>      # Configure the Sun Ray Connector for Windows Operating Systems
                            # Specify valid groupname to be used. See man page for details.
uttscadm -u                 # Unconfigure the Sun Ray Connector for Windows Operating Systems
uttscadm -r                 # Re-configure the Sun Ray Connector for Windows Operating Systems
uttscadm -m                 # Upgrade-configure the Sun Ray Connector for Windows Operating Systems
uttscadm -a                 # Use replies from utdialog_response.props if present
uttscadm -d                 # Use replies from utdialog_defaults.props if present
uttscadm -n                 # Return error if user interaction is required
uttscadm -h                 # Display this usage message
!
    exit $1

}

#Helpers for FIFOs used to get sensitive content out of command lines
#
#

CleanupPipeProcs() {
    [ -n "$PW_PID" ] && kill "$PW_PID" 2> /dev/null
}
 
CreatePipe() {
    mkfifo -m 600 "$1"
}

DestroyPipe() {
    rm -f "$1"
    [ -n "$2" ] && kill $2 2>/dev/null
}

CreateSecureFile() {
    touch "$1"
    chmod 600 "$1"
}

DestroySecureFile() {
     rm -f "$1"
}

CreatePWPipe_SunOS() {
    CreatePipe $TMP_PWPIPE || return 1
 
    print "$ROOTPW" > $TMP_PWPIPE &
    PW_PID=$!
}

DestroyPWPipe_SunOS() {
    DestroyPipe "$TMP_PWPIPE" "$PW_PID"
    PW_PID=
}

CreatePWPipe_Linux() {
	CreateSecureFile "$TMP_PWPIPE" || return 1
	print -n "$ROOTPW" > "$TMP_PWPIPE"
}

DestroyPWPipe_Linux() {
        DestroySecureFile "$TMP_PWPIPE"
}

CreatePWPipe() {

    case "$OS" in # {
    SunOS)
      CreatePWPipe_SunOS
    ;;

    Linux)
      CreatePWPipe_Linux
    ;;

    *)
      Fatal "unknown OS name $OS"
    ;;

    esac # }
}

DestroyPWPipe() {

    case "$OS" in # {
    SunOS)
      DestroyPWPipe_SunOS
    ;;

    Linux)
      DestroyPWPipe_Linux
    ;;

    *)
      Fatal "unknown OS name $OS"
    ;;

    esac # }
}

#

#
# function to get the LDAP port number from the utdsd.ini file
#
function get_ldap_port {
	if [[ -f ${SRDS_LDAP_CURRENT}/utdsd.ini ]]; then
		sed -n -e 's/^LdapPort=//p' ${SRDS_LDAP_CURRENT}/utdsd.ini
	else
		# utdsd.init does not exist under /etc/opt/SUNWut/srds/current
		# directory.  This can only happen when the system is being
		# configured the first time.  We get the default port from
		# the default directory.
		sed -n -e 's/^LdapPort=//p' ${SRDS_LDAP_DEFAULT}/utdsd.ini
	fi
}


function SetPlatformDependencies {

    case "$OS" in # {
    SunOS)
	LDAPADD="/usr/bin/ldapadd"
	LDAPDELETE="/usr/bin/ldapdelete"
	LDAPSEARCH="/usr/bin/ldapsearch -L"  # -L option ensures same ouput format on s9, s10
	LDAP_PWOPT="-j"
	DEFAULT_SSL_LIB=libssl.so.0.9.7
	DEFAULT_CRYPTO_LIB=libcrypto.so.0.9.7
	DEFAULT_PATHNAME="/usr/sfw/lib/libssl.so.0.9.7"
	ALTERNATE_PATHNAME="/usr/sfw/lib/libssl.so.0.9.8"
	TR_CMD="tr '[a-z][A-Z]' '[n-z][a-m][N-Z][A-M]' "
	;;
    Linux)
	LDAPADD="/usr/bin/ldapadd -h ${THIS_HOST} -x"
	LDAPDELETE="/usr/bin/ldapdelete -h ${THIS_HOST} -x"
	LDAPSEARCH="/usr/bin/ldapsearch -h ${THIS_HOST} -x"
	LDAP_PWOPT="-y"
	DEFAULT_SSL_LIB=libssl.so.0.9.7
	DEFAULT_CRYPTO_LIB=libcrypto.so.0.9.7
	#default path on 2.6 linux servers is /usr/lib for the libcrypto
	DEFAULT_PATHNAME="/usr/lib/libssl.so.0.9.7"
	ALTERNATE_PATHNAME="/lib/libssl.so.0.9.7a"
	TR_CMD="tr 'a-zA-Z' 'n-za-mN-ZA-M' "
	;;
    *)
	print -u2 "unknown OS name $OS"
	exit 1
	;;
    esac # }
}

function validateSRSSversion {

    Version=`$SUNWUTLIB/utprodinfo -p SUNWuto PRODVERS`
    majorVersion=`echo $Version | awk -F. '{print $1}'`
    minorVersion=`echo $Version | awk -F. '{print $2}'`

   if [[ $majorVersion -lt 4 || $majorVersion -eq 4 && ${minorVersion%%_*} -lt 0 ]]; then
     print "Only SRSS 4.0 and above are supported"
     exit 1
   fi
}

function mustBeConfigured {
#
# Check to see if utconfig has been run first by checking for the
# existence of /etc/opt/SUNWut/utadmin.conf
#
    if [[ ! -f $UTADMIN_CONF ]]
    then
        print -u2 "Please run utconfig first before configuring Sun Ray Connector for Windows Operating Systems."
	exit 1
    fi
}

# Read LDAP admin password from password file
# and decode it

function getPassword {

    if [[ ! -r $UTADMIN_PW ]]
    then
        print -u2 "Unable to read Sun Ray Data Store admin password. "
	exit 1
    fi

    ROOTPW=`$TR_CMD < $UTADMIN_PW`
}

PrintRestartMsg() {

     print -u2 "
*****************************************************************************
A restart of Sun Ray services is required before the Sun Ray Connector for 
Windows Operating Systems is used. Please run :

           $SUNWUTSBIN/utstart

Note that this will *NOT* terminate any sessions.
*****************************************************************************"

}

function createLDAPschema {

	OUTFILE=/tmp/ldap.add.tmp
	print "dn: utname=remoteclient,$ADMINSUBTREE" > $OUTFILE
	print "objectClass: utMap" >> $OUTFILE
	print "utname:  remoteclient" >> $OUTFILE

	CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP additions"

	${LDAPADD} -p $LDAP_PORT -D $ADMINUSERNAME  $LDAP_PWOPT $TMP_PWPIPE \
	   -f $OUTFILE
	DestroyPWPipe

	RETCODE=`echo $?`
	rm $OUTFILE

	print "dn: utname=users,utname=remoteclient,$ADMINSUBTREE" > $OUTFILE
	print "objectClass: utMap" >> $OUTFILE
	print "utname: users" >> $OUTFILE

	CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP additions"

	${LDAPADD} -p $LDAP_PORT -D $ADMINUSERNAME  $LDAP_PWOPT $TMP_PWPIPE \
	   -f $OUTFILE

	DestroyPWPipe

	rm $OUTFILE

}


function removeServicesEntry {
        awk -f - $ETCSERVICES <<!
                BEGIN { DOPRINT = 1; STATUS = 0 }

                /^$START_DELIMITER$/ {
                    if ( DOPRINT == 0 )
                        STATUS = 2
                    else
                        DOPRINT = 0
                }

                { if ( DOPRINT == 1 ) { print } }

                /^$END_DELIMITER$/ {
                    if ( DOPRINT == 1 )
                        STATUS = 2
                    else
                        DOPRINT = 1
                }

                END {
                    if ( DOPRINT == 0 )
                        exit 2
                    else
                        exit STATUS
                }
!
        if [[ $? != 0 ]]; then
            print -u2 "Error: '$ETCSERVICES' does not have SUNWuttsc entry correctly setup.\n" 1>&2
	    exit 1
        fi
}

function addServicesEntry {
        # Entry does not exist, add it.
        echo $START_DELIMITER 
        echo "$UTTSCPD         $UTTSCPDPORT                        # SRWC proxy daemon" 
        echo $END_DELIMITER
}


function removeLDAPschema {

	getPassword

	SEARCHBASE="utname=users,utname=remoteclient,$ADMINSUBTREE"

	CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP search"

	for user in `{
	    ${LDAPSEARCH} -p $LDAP_PORT -D "$ADMINUSERNAME" \
	    $LDAP_PWOPT $TMP_PWPIPE \
            -b "$SEARCHBASE" \
            -s one "utname=*" utname | grep "utname:" | awk '/utname: / {print $2}'
	}`
        do
            $UTTSCPRINTERADM -d $user
        done

	DestroyPWPipe

        OUTFILE=/tmp/ldap.del.tmp
        print "utname=users,utname=remoteclient,$ADMINSUBTREE" > $OUTFILE

	CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP deletions"

	${LDAPDELETE} -p $LDAP_PORT -D "$ADMINUSERNAME" \
	$LDAP_PWOPT $TMP_PWPIPE -f $OUTFILE

	DestroyPWPipe

	RETCODE=`echo $?`
        rm $OUTFILE

        print "utname=remoteclient,$ADMINSUBTREE" > $OUTFILE

	CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP deletions"

	${LDAPDELETE} -p $LDAP_PORT -D "$ADMINUSERNAME" \
	$LDAP_PWOPT $TMP_PWPIPE -f $OUTFILE

	DestroyPWPipe

        rm $OUTFILE

}

function setupProxyDaemon {

    #  Add an entry for the uttscpd in /etc/services files. 
    #
    grep "^$UTTSCPD" $ETCSERVICES >/dev/null 2>&1
    if [[ $? -ne 0 ]]; then
       addServicesEntry > $TMPFILE      
       cat $TMPFILE >> $ETCSERVICES
       rm $TMPFILE
     fi

    case "$OS" in # {
    Linux)
      chkconfig --add uttscp > /dev/null
    ;;

    esac # }

    
    # Launch SRDS Proxy daemon
    $SUNWUTTSC_LOC/sbin/uttscrestart


}

function removeProxyDaemon {

    # Stop SRDS Proxy Daemon
    /etc/init.d/uttscp stop

    # Remove entry from /etc/services file
    grep "^$UTTSCPD" $ETCSERVICES >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        removeServicesEntry > $TMPFILE
	cp $TMPFILE $ETCSERVICES
	rm $TMPFILE
    fi

    case "$OS" in # {
    Linux)
      chkconfig --del uttscp > /dev/null
    ;;

    esac # }

}

function setupLDAP {

    #    Call the script to update permissions in ldap for creating new
    #    branch. Stop and start the Sun Ray Data store process.
    #    Do all this only if schema doesn't already exist and only on primary.

    if ! $SUNWUTSBIN/utreplica -i | grep "UT_Replica_Id_Sec" > /dev/null 2>&1; then
    
      getPassword

      # Do search and throw away OUTPUT.. this prevents it from being 
      # displayed on screen
      
      SEARCHBASE="utname=users,utname=remoteclient,$ADMINSUBTREE"

      CreatePWPipe ||
	   Fatal "Cannot create pipe $TMP_PWPIPE for required LDAP search"

      OUTPUT=`{
	${LDAPSEARCH} -p $LDAP_PORT -D "$ADMINUSERNAME" \
	$LDAP_PWOPT $TMP_PWPIPE \
        -b "$SEARCHBASE" "utname=*" 2>&1 > /dev/null 
      }` 
      
      RETURNSTATUS=`echo $?`
      DestroyPWPipe
      
      # ldapsearhc returns 0 if it is successful in finding a match. Non-zero
      # otherwise.
      if [[ $RETURNSTATUS != 0 ]]
      then		  
	  # 4. Create LDAP schema for printer cache storage.
	
	  print "Creating required LDAP schema ... "
	  createLDAPschema
	  if [ $RETCODE == 0 ] 
	  then
	      print "Done."
	      PrintRestartMsg
	  fi
      else
	print "Data Store schema already in place. No change Required."
	
      fi
    fi
}

function configTSC {

    if ! $upgrade ; then
	setupLDAP
    fi
           # Setup and start the daemon
    setupProxyDaemon
}


function unconfigTSC {

    # Activities to be done at un-config time are :
    # 1. Remove LDAP schema for printer cache storage.
    # 2. Remove uttsc-bin and uttscpd links
    # 3. Remove the files under /etc/opt/SUNWuttsc/lib and the directory too 


    if [[ -f $SUNWUTTSCLIB/uttsc-bin ]] 
    then
      rm -rf $SUNWUTTSCLIB/uttsc-bin
    fi


    if [[ -f $SUNWUTTSCLIB/uttscpd ]] 
    then
      rm -rf $SUNWUTTSCLIB/uttscpd
    fi


   rm -rf  $SUNWUTTSCETCLIB/uttsc-bin
   rm -rf  $SUNWUTTSCETCLIB/uttscpd
   rm -rf  $SUNWUTTSCETC

   # Stop and unconfig SRDS Proxy Daemon
   removeProxyDaemon	  

    if [[ ! -f $UTADMIN_CONF ]]
    then
        exit 0 
    fi
    
    # if configured, then set the admin variables
    setAdminVars

    if ! $SUNWUTSBIN/utreplica -i | grep "UT_Replica_Id_Sec" > /dev/null 2>&1; then
        print "Removing LDAP schema ..."

        removeLDAPschema
	if [ $RETCODE == 0 ] 
	then
	      print "Done."
	else
	      print "Unconfig failed."
	fi
    fi
 
   #If utadmin.conf exists then it needs to be updated
    if [[ -f $UTADMIN_CONF ]]; then
	cp -p "$UTADMIN_CONF" "$TMP_ADM_FILE"
	sed "s/^\(admin.srwc.groupname[ 	]*=\).*/\1/" \
	    "$TMP_ADM_FILE" > "$UTADMIN_CONF"
	rm $TMP_ADM_FILE    
    fi
}

function updateGroup {


    chgrp $GROUPNAME $SUNWUTTSCLIB/uttsc-bin 
    if [  $? != 0 ] 
    then
      print -u2 "\nInvalid groupname $GROUPNAME or unable to set groupname."
      exit 1
    fi
    chgrp $GROUPNAME $SUNWUTTSCLIB/uttscpd
    if [  $? != 0 ] 
    then
      print -u2 "\nInvalid groupname $GROUPNAME or unable to set groupname."
      exit 1
    fi

    # Ensure that the mode settings are as needed for uttsc-bin after the chgrp 
    # operation.
    chmod 02755 $SUNWUTTSCLIB/uttsc-bin
    if [  $? != 0 ] 
    then
      print -u2 "\nUnable to reset mode for  $SUNWUTTSCLIB/uttsc-bin."
      exit 1
    fi

    grep "admin.srwc.groupname" "$UTADMIN_CONF" > /dev/null
    if [ $? -eq 0 ]; then
	#The entry is there and only needs to be updated
	cp -p "$UTADMIN_CONF" "$TMP_ADM_FILE"
	sed "s/^\(admin.srwc.groupname[ 	]*=\).*/\1 ${GROUPNAME}/" \
	    "$TMP_ADM_FILE" > "$UTADMIN_CONF"
	rm $TMP_ADM_FILE    
    else
	# There is no entry at all, write a new entry
	echo "admin.srwc.groupname	= $GROUPNAME" >> $UTADMIN_CONF
    fi


}

#
# Copy the uttscpd and uttsc-bin files from prtotype delivery area to the main lib directory. 
# Preserve timestamps. Set the group on these binaries
#

function setupBinaryFiles {

        if [[ ! -d $SUNWUTTSCETCLIB ]]
	then
            mkdir -p $SUNWUTTSCETCLIB 
	    if [  $? != 0 ] 
	    then
	      print -u2 "\n Unable to create directory $SUNWUTTSCETCLIB."
	      exit 1
	    fi
	fi

	cp -fp $SUNWUTPROTO/uttsc-bin $SUNWUTTSCETCLIB
	if [  $? != 0 ] 
	then
	  print -u2 "\n Unable to copy uttsc-bin from prototype directory."
	  exit 1
	fi

	cp -fp $SUNWUTPROTO/uttscpd $SUNWUTTSCETCLIB
	if [  $? != 0 ] 
	then
	  print -u2 "\nUnable to copy uttscpd from prototype directory."
	  exit 1
	fi

	# Create links from lib directory
	if [[ ! -L $SUNWUTTSCLIB/uttsc-bin ]] then
	    ln -s $SUNWUTTSCETCLIB/uttsc-bin $SUNWUTTSCLIB/uttsc-bin
	fi

	if [[ ! -L $SUNWUTTSCLIB/uttscpd ]] then
	    ln -s $SUNWUTTSCETCLIB/uttscpd $SUNWUTTSCLIB/uttscpd
	fi

	# Create link for other libraries from new ORIGIN
	if [[ ! -L $SUNWUTTSCETCLIB/lib ]] then
	    ln -s $SUNWUTTSCLIB $SUNWUTTSCETCLIB/lib
	fi
}

UTDIALOG=/etc/opt/SUNWut/basedir/lib/utdialog

function promptForSRWCGroupname {

  USE_EXISTING_GROUP_DEFAULT=Y
  while ! $SRWC_GROUP_OK
  do
    SRWC_GROUP=$($UTDIALOG $UTDIALOG_OPTS utconfig.uttscadm.Groupname)

    if GroupExists "$SRWC_GROUP"; then
        print -u2 "The group '$SRWC_GROUP' already exists."
	print -u2 "A dedicated group should be used for SRWC."
	if [ -z "$USE_EXISTING_GROUP_DEFAULT" ]; then
	    print -u2 "Dialog loop detected - eliminating default"
	fi
	# Note ReplyYesOrNo pre-pends "utconfig." to key name
	if ReplyYesOrNo uttscadm.UseExistingGroupYN "$USE_EXISTING_GROUP_DEFAULT"; then
	    SRWC_GROUP_ID=""
	    SRWC_GROUP_OK=true 
	else
	    # break potential dialog loop
	    $UTDIALOG -c SRWC -w "utconfig.uttscadm.UseExistingGroupYN="
	    USE_EXISTING_GROUP_DEFAULT=
	fi
    else
	if IsValidGroup $SRWC_GROUP ; then
	    while ! $SRWC_GID_OK
	      do
	      SRWC_GID=$($UTDIALOG $UTDIALOG_OPTS utconfig.uttscadm.GroupID)
	      if [ "$SRWC_GID" = "auto" ]; then
		SRWC_GID_OK=true
	      else
		if IsValidInteger $SRWC_GID && (( $SRWC_GID > 100 )); then
		  SRWC_G_OPTS="-g $SRWC_GID"
		  SRWC_GID_OK=true
		else
		  print -u2 "Group id's must start after 100 and must be an integer"
		  print -n -u2 "Re-"
		  SRWC_GID=""
		  $UTDIALOG -c SRWC -w "utconfig.uttscadm.GroupID="
		fi
	      fi
	    done
	    SRWC_GROUP_OK=true     	
	else
	    print -n "Group must begin with a lowercase alphabetic character and may only consist of lower case alphabetic characters and numeric characters"
	fi
    fi
    if ! $SRWC_GROUP_OK ; then
	    print -u2 -n "\nRe-"
	    $UTDIALOG -c SRWC -w "utconfig.uttscadm.Groupname="
    else
	if ! GroupExists "$SRWC_GROUP" ;then
	    groupadd $SRWC_G_OPTS $SRWC_GROUP
	    
	    if [ $? != 0 ]; then
		SRWC_GROUP_OK=false
		SRWC_GID_OK=false
		print -u2 "Error creating groupname $SRWC_GROUP with gid $SRWC_GID"
		print -u2 -n "\nRe-"
		$UTDIALOG -c SRWC -w "utconfig.uttscadm.Groupname="
		$UTDIALOG -c SRWC -w "utconfig.uttscadm.GroupID="
	    fi
	fi
    fi
  done
}
#
# MAIN
#

mustBeRoot
LDAP_PORT=$(get_ldap_port)

SetPlatformDependencies

#
# Parse and validate command line options
#
UTDIALOG_OPTS="-c SRWC"
NSET=0
upgrade=false
config=false
unconfig=false
reconfig=false
force=false

while getopts acduhrnmfg: name
do
        case $name in
	  a|d|n)
	     UTDIALOG_OPTS="$UTDIALOG_OPTS -$name"
	     ;;
	  c)
	     config=true
	     let "NSET = NSET + 1"
	     ;;
	  g)
	     GROUPNAME="$OPTARG"
	     ;;
	  m)
	     upgrade=true
	     let "NSET = NSET + 1"
	     ;;
	  r)
	     reconfig=true
	     let "NSET = NSET + 1"
	     ;;      
	  u)
	     unconfig=true
	     let "NSET = NSET + 1"
	     ;;
          f)
	     force=true
	     ;;
	  h)
	     Usage 0
	     ;;
	  ?)
	     Usage 1
	     ;;
        esac
done

if [ $NSET != 1 ] 
then
      print -u2 "One (and only one) of the [-c][-r][-u] [-m] options must be specified."
      Usage 1
fi


if $config || $upgrade ; then
      if [ -z "$GROUPNAME" ]; then
	  if  ! $force && ! $upgrade  ; then
	      #Check if already configured.
	      key=admin.srwc.groupname
	      ADMIN_GROUPNAME=$(sed -n -e "s/^[ 	]*${key}[ 	]*=[ 	]*//p" $UTADMIN_CONF 2>/dev/null)
	      BIN_GROUPNAME="$(ls -lL $SUNWUTTSCLIB/uttsc-bin 2>/dev/null | awk -F" " '{print $4}')"
	      if [ -n "$ADMIN_GROUPNAME" ] && [ -n "$BIN_GROUPNAME" ] ; then		  
		  if [ "$ADMIN_GROUPNAME" == "$BIN_GROUPNAME" ]; then
		      print "Current Sun Ray Windows Connector configuration:"
		      print "  Windows Connector group name: $ADMIN_GROUPNAME"
		      if ReplyYesOrNo uttscadm.ChangeCurrentConfigYN "Y" ; then
			  promptForSRWCGroupname
			  GROUPNAME=$SRWC_GROUP
		      else
			  exit 0
		      fi
		  else 
		      print "Error: Windows Connector configuration out of sync"
		  fi
	      elif [ -n "$ADMIN_GROUPNAME" ] ||  [ -n "$BIN_GROUPNAME" ]; then
		  # Even if one of them is defined it's an out-of-sync-issue
		      print "Error: Windows Connector configuration out of sync"
	      fi
	      promptForSRWCGroupname
	      GROUPNAME=$SRWC_GROUP       
	  else 
	      key=admin.srwc.groupname
	      GROUPNAME=$(sed -n -e "s/^[ 	]*${key}[ 	]*=[ 	]*//p" $UTADMIN_CONF 2>/dev/null)
	      if  [ -z "$GROUPNAME" ]; then
		  GROUPNAME="$(ls -lL $SUNWUTTSCLIB/uttsc-bin 2>/dev/null | awk -F" " '{print $4}')"  
		  if [ -z "$GROUPNAME" ]; then 
		      print "Windows Connector groupname not configured.\nFailing force/silent mode configuration for Sun Ray Windows Connector.\nPlease run $SUNWUTSBIN/utconfig -c to configure Windows Connector Software." 
		      exit 1
		  elif [[ $GROUPNAME = "root" ]] || [[ $GROUPNAME = "sys" ]] ;then
		      print "groupname should not be root or sys.\nFailing force/silent mode configuration for Sun Ray Windows Connector.\nPlease run $SUNWUTSBIN/utconfig -c to configure Windows Connector Software."
		      exit 1
		  fi

	      fi
	  
	  fi
      fi

      cat /etc/group | awk -F: '{print $1}' | grep -w $GROUPNAME > /dev/null
      if [ $? != 0 ]
      then
	  print -u2 "Invalid groupname : $GROUPNAME. Please specify an existing groupname."
	  exit 1
      fi

      if [[ $GROUPNAME = "root" ]] || [[ $GROUPNAME = "sys" ]] ;then
	  print "groupname should not be root or sys.\nFailing force/silent mode configuration for Sun Ray Windows Connector.\nPlease run $SUNWUTSBIN/utconfig -c to configure Windows Connector Software."
	  exit 1
      fi


      if $config ; then
	  validateSRSSversion
	  mustBeConfigured
      fi
      setAdminVars
      setupBinaryFiles
      updateGroup
      configTSC      
fi

if $unconfig ; then
    unconfigTSC  
fi

if $reconfig ; then
    setupBinaryFiles  
fi

