#!/bin/ksh
#
# ident "uttscadm.ksh $Date $Revision: 2200 $ SMI"
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

# Admin CLI used for configuring the Sun Ray Connector

trap "stty echo </dev/tty; exit 1" HUP INT QUIT TERM

SUNWUTETC=/etc/opt/SUNWut
SUNWUTLIB=/opt/SUNWut/lib
SUNWUTTSCLIB=/opt/SUNWuttsc/lib  #### Make this relocatable ###
UTADMIN_CONF=$SUNWUTETC/utadmin.conf
UTADMIN_PW=$SUNWUTETC/utadmin.pw
THIS_HOST=$(uname -n)
ETC_OPT_UT="/etc/opt/SUNWut"
SRDS_LDAP_DEFAULT="${ETC_OPT_UT}/srds/default"
SRDS_LDAP_CURRENT="${ETC_OPT_UT}/srds/current"
PATH="/usr/sbin:/usr/bin:/sbin:/bin"
UTTSCPRINTERADM=/opt/SUNWuttsc/sbin/uttscprinteradm
UTDSD_CMD=/etc/init.d/utds
SRSS_PKG_LOC="`$SUNWUTETC/basedir/lib/utprodinfo -r SUNWuto`/SUNWut"
SRSS_DYNAMIC_ADMIN=$SRSS_PKG_LOC/lib/libutadmin.so.1

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

RETCODE=0
ROOTPW=""

function checkForPatch {

        if [[ ! -f $SRSS_DYNAMIC_ADMIN ]]; then
	      print -u2 "Unable to configure the Sun Ray Connector. Please ensure that the latest SRSS patch is installed."
	      exit 1
	fi	  
}


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         # Configure the Sun Ray Connector for Windows Operating Systems
uttscadm -u         # Unconfigure the Sun Ray Connector for Windows Operating Systems
uttscadm -h         # Display this usage message
!
    exit $1

}

#
# 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 {
    OS=`/bin/uname -s`

    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
	DEFAULT_SSL_LIB=libcrypto.so.0.9.7
	DEFAULT_PATHNAME="/usr/sfw/lib/libcrypto.so.0.9.7"
	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"
	DEFAULT_SSL_LIB=libcrypto.so.0.9.6
	DEFAULT_PATHNAME="/lib/libcrypto.so.0.9.6b"
	TR_CMD=" tr a-zA-Z n-za-mN-ZA-M "
	;;
    *)
	print -u2 "unknown OS name $OS"
	exit 1
	;;
    esac # }
}


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 :

           /opt/SUNWut/sbin/utrestart

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

	
	${LDAPADD} -p $LDAP_PORT -D $ADMINUSERNAME  -w $ROOTPW -f $OUTFILE

	RETCODE=`echo $?`
	rm $OUTFILE

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

	${LDAPADD} -p $LDAP_PORT -D $ADMINUSERNAME  -w $ROOTPW -f $OUTFILE

	rm $OUTFILE

}

function removeLDAPschema {

	getPassword

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

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

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

	${LDAPDELETE} -p $LDAP_PORT -D "$ADMINUSERNAME" -w $ROOTPW -f $OUTFILE

	RETCODE=`echo $?`
        rm $OUTFILE

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

	${LDAPDELETE} -p $LDAP_PORT -D "$ADMINUSERNAME" -w $ROOTPW -f $OUTFILE

        rm $OUTFILE

}

function configTSC {

    # Activities to be done at config time are :
    # 1. Check for SRSS version.. as only 3.1 and above are supported

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

    if [[ $majorVersion -lt 3 || $majorVersion -eq 3 && $minorVersion -lt 1 ]]; then
	print "Only SRSS 3.1 and above are supported"
	exit 1
    fi

    checkForPatch

    # 2. Prompt for OpenSSL path and create a symbolic link from /opt/SUNWuttsc/lib
    # to the libcrypto library. If this link already exists, display the link value 
    # and continue.

    if  [[ -L $SUNWUTTSCLIB/$DEFAULT_SSL_LIB ]]
    then
        linkname=`ls -l $SUNWUTTSCLIB/$DEFAULT_SSL_LIB | awk '{print $NF}'`
      	print "OpenSSL library already linked to: " $linkname 
	print "Continuing.."
    else
        UT_PATHNAME_OK=false
	
	while ! $UT_PATHNAME_OK
	do 
	    print -n "Enter complete location for $DEFAULT_SSL_LIB  [$DEFAULT_PATHNAME]: "
	    read -r
	    case "$REPLY" in 
	      "")		  
		  PATHNAME=$DEFAULT_PATHNAME
		  if [[ -f $PATHNAME ]]
		  then
		      UT_PATHNAME_OK=true
		      print "Creating link ...\n"
		      ln -s $PATHNAME $SUNWUTTSCLIB/$DEFAULT_SSL_LIB
		  else
		      print -u2 "\n Invalid filename $DEFAULT_PATHNAME"
		  fi
		  ;;
	      *)
		   PATHNAME=$REPLY
		   if [[ -f $PATHNAME ]]
		   then
		       UT_PATHNAME_OK=true
		       print "\n Creating link ...\n"
		       ln -s $PATHNAME $SUNWUTTSCLIB/$DEFAULT_SSL_LIB
		   else
		     print -u2 "\n Invalid filename $REPLY "
		   fi
		   ;;
	    esac
	    
	done	    
    fi

    # 3. 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 ! /opt/SUNWut/sbin/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"

      OUTPUT=`${LDAPSEARCH} -p $LDAP_PORT -D "$ADMINUSERNAME" -w $ROOTPW \
          -b "$SEARCHBASE" "utname=*" 2>&1 > /dev/null ` 
      
      RETURNSTATUS=`echo $?`
      
      # ldapsearhc returns 0 if it is successful in finding a match. Non-zero
      # otherwise.
      if [[ $RETURNSTATUS != 0 ]]
      then		  
	  if [[ -e $SUNWUTLIB/utdsupdate ]]
	  then
	    
	    $UTDSD_CMD stop
	    
	    $SUNWUTLIB/utdsupdate
	    
	    # Restart the SRDS
	    $UTDSD_CMD start
	  fi
	  
	  
	  # 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 unconfigTSC {

    # Activities to be done at un-config time are :
    # 1. Remove the libcrypto library link from /opt/SUNWut/lib 
    # 2. Remove LDAP schema for printer cache storage.

    print "\n removing $SUNWUTTSCLIB/$DEFAULT_SSL_LIB"
    rm -rf $SUNWUTTSCLIB/$DEFAULT_SSL_LIB

    if [[ ! -f $UTADMIN_CONF ]]
    then
        exit 0 
    fi

    if ! /opt/SUNWut/sbin/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
}

mustBeRoot
LDAP_PORT=$(get_ldap_port)

SetPlatformDependencies

if [[ $# -ne 1 ]]; then
	Usage 1
fi

case "$1" in 
'-c')
	mustBeConfigured
    	configTSC
    ;;
'-u')
	unconfigTSC
	;;
'-h')
        Usage 0
	;;
*)
        Usage 1
	;;
esac
