#! /bin/ksh 

#
# ident "%W%    %E% SMI"
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# Admin CLI used for configuring the Sun Ray Connector
#

SUNWUTETC=/etc/opt/SUNWut
SUNWUTLIB=/opt/SUNWut/lib
SUNWUTTSCLIB=/opt/SUNWuttsc/lib  #### Make this relocatable ###
UTADMIN_CONF=$SUNWUTETC/utadmin.conf
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

ROOTDN="cn=utadmin,utname=${THIS_HOST},o=v1,o=utdata"


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"
	DEFAULT_SSL_LIB=libcrypto.so.0.9.7
	DEFAULT_PATHNAME="/usr/sfw/lib/libcrypto.so.0.9.7"
	;;
    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"
	;;
    *)
	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
}


SubstituteMacros() {
  sed "
    s
@(THIS_HOST)
$THIS_HOST
g
  " $1

  return $?
}

function getPassword {
	while true; do
		print -n "Enter LDAP admin password: "
        	stty -echo
        	read -r
        	stty echo
        	print ""
		length=`echo $REPLY | awk '{print length()}'` 
		if [[ length -lt 5 ]]; then
			print "Invalid password, try again"
		else
			break
		fi
	done
        ROOTPW=$REPLY
}


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 {

	getPassword

	OUTFILE=/tmp/ldap.add.tmp
	print "dn: utname=remoteclient,utname=@(THIS_HOST),o=v1,o=utdata" > $OUTFILE
	print "objectClass: utMap" >> $OUTFILE
	print "utname:  remoteclient" >> $OUTFILE

	SubstituteMacros $OUTFILE |
            ${LDAPADD} -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW

	rm $OUTFILE

	print "dn: utname=users,utname=remoteclient ,utname=@(THIS_HOST),o=v1,o=utdata" > $OUTFILE
	print "objectClass: utMap" >> $OUTFILE
	print "utname: users" >> $OUTFILE

	SubstituteMacros $OUTFILE |
            ${LDAPADD} -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW

	rm $OUTFILE

}

function removeLDAPschema {

	getPassword

	for user in `${LDAPSEARCH} -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW \
            -b "utname=users,utname=remoteclient,utname=$THIS_HOST,o=v1,o=utdata" \
            -s one "utname=*" utname | grep "utname:" | awk '/utname: / {print $2}'`
        do
            $UTTSCPRINTERADM -d $user
        done

        OUTFILE=/tmp/ldap.add.tmp
        print "utname=users,utname=remoteclient,utname=$THIS_HOST,o=v1,o=utdata" > $OUTFILE

	SubstituteMacros $OUTFILE |
            ${LDAPDELETE} -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW

        rm $OUTFILE

        print "utname=remoteclient,utname=@(THIS_HOST),o=v1,o=utdata" > $OUTFILE

	SubstituteMacros $OUTFILE |
            ${LDAPDELETE} -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW

        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

     # 2. Prompt for OpenSSL path and create a symbolic link from /opt/SUNWuttsc/lib
     # to the libcrypto library

    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

     # 3. Call the script to update permissions in ldap for creating new
     #    branch. Stop and start the Sun Ray Data store process.

    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.

    if ! /opt/SUNWut/sbin/utreplica -i | grep "UT_Replica_Id_Sec" > /dev/null 2>&1; then
        print "Creating required LDAP schema ... "
        createLDAPschema
        print "Done."
    fi

    PrintRestartMsg
}


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 ! /opt/SUNWut/sbin/utreplica -i | grep "UT_Replica_Id_Sec" > /dev/null 2>&1; then
        print " Removing LDAP schema ..."
        removeLDAPschema
        print "Done."
    fi
}

mustBeRoot
mustBeConfigured
LDAP_PORT=$(get_ldap_port)

SetPlatformDependencies

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

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