#!/bin/sh 

# Copyright  2004 Sun Microsystems, Inc. All rights reserved. 
# 
# Sun Microsystems, Inc. has intellectual property rights relating to
# technology embodied in the product that is described in this document.
# In particular, and without limitation, these intellectual property rights
# may include one or more of the U.S. patents listed at
# http://www.sun.com/patents and one or more additional patents or pending
# patent applications in the U.S. and in other countries.
# 
# U.S. Government Rights - Commercial software. Government users are subject
# to the Sun Microsystems, Inc. standard license agreement and applicable
# provisions of the FAR and its supplements.
# 
# Use is subject to license terms. 
# 
# This distribution may include materials developed by third parties. Sun,
# Sun Microsystems, the Sun logo, Java and Sun[tm] ONE are trademarks or
# registered trademarks of Sun Microsystems, Inc. in the U.S. and other
# countries. 
# 
# Copyright  2004 Sun Microsystems, Inc. Tous droits rservs. Sun
# Microsystems, Inc. dtient les droits de proprit intellectuels relatifs
#  la technologie incorpore dans le produit qui est dcrit dans ce document.
# En particulier, et ce sans limitation, ces droits de proprit
# intellectuelle peuvent inclure un ou plus des brevets amricains lists
#  l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires
# ou les applications de brevet en attente aux Etats - Unis et dans les
# autres pays.
# 
# L'utilisation est soumise aux termes du contrat de licence.
# 
# Cette distribution peut comprendre des composants dvelopps par des
# tierces parties.
# 
# Sun, Sun Microsystems, le logo Sun, Java et Sun[tm] ONE sont des marques
# de fabrique ou des marques dposes de Sun Microsystems, Inc. aux
# Etats-Unis et dans d'autres pays.


# Tag swapped variables

    BASE=BASEDIR
    IWS_SERVER_HOME=WS61_HOME
    WS_INSTANCE=$IWS_SERVER_HOME/WS61_INSTANCE
    JSS_HOME=JSSHOME
    NSS_PATH=NSSHOME/usr/lib/mps
    NSPR_PATH=NSPRHOME/usr/lib/mps

# Derived variables

    PRODUCTDIR=${PRODUCT_DIR}
    PACKAGEDIR=$BASE/${PRODUCTDIR}
    WEBAPPDIR=$BASE/${PRODUCTDIR}/web-apps
    SERVICEAPPSDIR=$WEBAPPDIR/services
    AGENTAPPSDIR=$WEBAPPDIR/agent

    AMCONFIG=$PACKAGEDIR/lib
    AMCONF_DIR=IS_INSTALL_ETCDIR/IS_PRODNAME/config
    AMCONFIG=${AMCONF_DIR}/AMConfig.properties
    PLATFORMBINDIR=${PACKAGEDIR}/bin
    PLATFORMSHAREDIR=${PACKAGEDIR}/share/bin
    WTPASSFILE=${PACKAGEDIR}/config/.wtpass

    IPS_TMP=IS_INSTALL_VARDIR/${PRODUCTDIR}

    DEFAULTUNIXHELPERPORT=58946
    DEFAULTSECURIDHELPERPORT=58943

    UNIXHELPER=${PACKAGEDIR}/share/bin/amunixd
    SECURIDHELPER=${PACKAGEDIR}/share/bin/amsecuridd

    export IWS_SERVER_HOME
    WS_ADMIN="$IWS_SERVER_HOME/https-admserv"
    ECHO=/usr/bin/echo
    UNAME=/bin/uname

    JSS_JAR_PATH=${JSS_HOME}/usr/share/lib/mps
    JAXP_JAR_PATH=${PACKAGEDIR}/lib

    gettext=/usr/bin/gettext
#Special characters to be used for translated messages. 
#These characters are present in translated messages, they are not displayed 
#correctly if we use eval in the echo. In such cases these variables
#may be used
    APOS="'"
    BQUOTE="\`"
    TILDE="~"

    TEXTDOMAIN=dpscripts
    TEXTDOMAINDIR=${PACKAGEDIR}/locale

    PRODUCTNAME="`/usr/bin/gettext 'Sun Java System Identity Server'`"

    export TEXTDOMAIN
    export TEXTDOMAINDIR
    export LANG


    OSTYPE=`/bin/uname -s`
    if [ "$OSTYPE" = "Linux" ]; then
    	PS=/bin/ps
	GREP=/bin/grep
	ECHO=/bin/echo
	UNAME=/bin/uname
    else
    	PS=/usr/bin/ps
	GREP=/usr/bin/grep
	ECHO=/usr/bin/echo
	UNAME=/usr/bin/uname
    fi

    check_rc_script() {
        if [ "$0" = "S42amserver" ] || [ "$0" = "K42amserver" ]; then
	    if [ ! -f "$WTPASSFILE" ]; then
		exit 0
	    fi
	fi
    }

    ###############################################
    #
    # test for root user
    #

    check_root_user() {
	    uid=`/usr/xpg4/bin/id -u`
	    if [ "$uid" != "0" ];
	    then
		    echo "`$gettext 'You must be root user to run'` $0."
		    exit 1
	    fi
    }
    get_data() {
            HOSTNAME_FULL="`/bin/uname -n`"
            HOSTNAME=`echo "$HOSTNAME_FULL" | cut -d. -f1`
	    fulldomain=`domainname`

	    #
	    # first try and ping host.fulldomain
	    #

	    /usr/sbin/ping "$HOSTNAME.$fulldomain" > /dev/null 2>&1
	    if [ $? -eq 0 ]; then
		    #
		    # success, set domain and sub domain accordingly
		    #
		    SUBDOMAIN=`echo "$fulldomain" | cut -d. -f1` 
			    DOMAIN=`echo "$fulldomain" | cut -d. -f2-`
			    #set_cookie_domain $DOMAIN
			    LOCALHOST="$HOSTNAME.$SUBDOMAIN.$DOMAIN"
	    fi

            SERVER_DIR=$PACKAGEDIR/servers/https-$AMSERVERHOST

    }

    # kill daemon process
    killdaemonproc() {
	    pid=`$PS -ef | $GREP $1 | $GREP -v grep | /usr/bin/awk '{printf "%s ", $2}'`  

		    if [ "$pid" != "" ]; then
			    kill $pid >/dev/null 2>&1
			    sleep 2
			    kill -9 $pid >/dev/null 2>&1
		    fi
    }

    # find the named process(es)
    findproc() {
	    pid=`$PS -ef |
	    $GREP -w $1 | 
		    $GREP Djava.home |
		    $GREP -v grep |
		    /usr/bin/awk '{print $2}'`
		    echo $pid
    }

    check_for_ds() {
        if [ -z "$LDAPDIR" ]; then
            ds="no";
        else
            ds="yes";
        fi
    }

    check_for_ws() {
	    pkginfo SUNWamws > /dev/null 2>&1
	    if [ $? -eq 0 ]; then
		    ws="yes"
	    else 
		    ws="no"
	    fi
    }

    # kill the named process(es) (borrowed from S15nfs.server)
    killproc() {
	    pid=`findproc $1`
	    [ "$pid" != "" ] && kill $pid
    }

    check_for_running_ds() {
  	pid=`$PS -ef | $GREP ns-slapd | $GREP "$NDS_SERVER -i" | /usr/bin/awk '{ printf "%s", $2 }'`
		if [ "$pid" != "" ]; then
			running_ds="yes"
		else
			running_ds="no"
		fi
    }

setup_logs() {
    if [ "$1" = "showlog" ]; then
        LOG="/dev/stdout"
        export LOG
    else
        LOG="/dev/null"
        export LOG
    fi
}

stop_ds() {
	check_for_ds
	if [ "$ds" = "no" ]; then
		return
	fi

#	eval $NDS_SERVER/stop-slapd $LOG
	$NDS_SERVER/stop-slapd > $LOG 2>&1

	PIDFILE=$NDS_SERVER/logs/pid
	if [ -f $PIDFILE ]; then
		pid=`cat $PIDFILE`
		if [ "$pid" != "" ]; then
			kill_nice $pid
		fi
		/usr/bin/rm -f $PIDFILE
	fi
}


    stop_helpers() {
        echo "`$gettext 'stopping auth helpers ... '`"
        killdaemonproc $UNIXHELPER
	if [ "$OSTYPE" != "Linux" ]; then
		killdaemonproc $SECURIDHELPER
	fi	
	echo "`$gettext 'done.'`"
    }

    start_helpers() {
        echo "`$gettext 'starting auth helpers ... '`"
        unixparam=`getunixparam`
	securidparam=`getsecuridparam`

	if [ "$NLSPATH" = "" ]; then
	    NLSPATH=/usr/lib/locale/C/LC_MESSAGES
	else
	    NLSPATH=$NLSPATH:/usr/lib/locale/C/LC_MESSAGES
	fi
        
        unameval="`$UNAME -p`"
	#securid is available for sparc alone. 
        if [ "$securidparam" != "" ] && [ "$unameval" = "sparc" ]
	then
		#
		#  LD_LIBRARY_PATH set here if not set earlier
		#
		LD_LIBRARY_PATH=PKGDIR/lib:${LD_LIBRARY_PATH}
		export LD_LIBRARY_PATH
		export NLSPATH
		for i in $securidparam
		do
		    $SECURIDHELPER -c $i &
		done
	fi

        if [ "$unixparam" != "" ]
        then
		export NLSPATH
                $UNIXHELPER $unixparam &
        fi
	echo "`$gettext 'done.'`"
    }


    start_server_instances() {
        cd $PLATFORMBINDIR
        for aminstance in `ls | grep amserver`
        do
           in=`echo $aminstance | cut -d"." -f2`
           if [ "$in" = "" ]; then
              continue
           elif [ "$in" = "amserver" ]; then
              continue
           elif [ "$in" = "instance_template" ]; then
              continue
           else 
                echo "`$gettext 'running:'`  ./$aminstance start"
                ./$aminstance start
           fi
        done
    }

    stop_server_instances() {
        cd $PLATFORMBINDIR
        for aminstance in `ls | grep amserver`
        do
           in=`echo $aminstance | cut -d"." -f2`
           if [ "$in" = "" ]; then
              continue
           elif [ "$in" = "amserver" ]; then
              continue
           elif [ "$in" = "instance_template" ]; then
              continue
           else 
                echo "`$gettext 'running:'`  ./$aminstance stop"
                ./$aminstance stop
           fi
        done
    }

    getsecuridparam() {
	# see if securid enabled
	securid_enabled=`grep "com.iplanet.am.daemons=" $AMCONFIG | grep -i securid`
	securid_ports=`grep "securidHelper.ports=" $AMCONFIG | sed -e "s/securidHelper.ports=//"`
	if [ "$securid_enabled" != "" ]
	then
	    $ECHO "$securid_ports\c"
	fi
	echo ""
    }


    getunixparam() {
    	# see if unix enabled
    	unix_enabled=`grep "com.iplanet.am.daemons=" $AMCONFIG | grep -i unix`
    	if [ "$unix_enabled" != "" ]
    	then
    	# get unix helper trusted ip addresses
	   	UNIXIPADDR=`grep "unixHelper.ipaddrs=" $AMCONFIG | sed -e "s/unixHelper.ipaddrs=//"`
	   	UNIXIPPARAM=""
	   	if [ "$UNIXIPADDR" != "" ]
		then
		    NUMIP=0
		    for ipaddr in $UNIXIPADDR
		    do
			UNIXIPPARAM="$UNIXIPPARAM -a $ipaddr"
			NUMIP=`expr $NUMIP + 1`
		    done
		    UNIXIPPARAM="-i $NUMIP $UNIXIPPARAM"
		fi
		UNIXHELPERPORT=`grep "unixHelper.port=" $AMCONFIG | sed -e "s/unixHelper.port=//"`
		if [ "$UNIXHELPERPORT" = "" ]
		then
		    UNIXHELPERPORT=$DEFAULTUNIXHELPERPORT
		fi
		$ECHO "-c $UNIXHELPERPORT $UNIXIPPARAM \c"
	fi
	echo ""
    }
    ## remove the lock files

    remove_lock_files() {
	    if [ -d $NDS_SERVER/locks ] 
	    then
		    echo "`$gettext 'removing'` $NDS_SERVER/locks\c"
		    /usr/bin/rm -rf $NDS_SERVER/locks
		    echo "`$gettext '...done'`"
	    fi
	    if [ -f $NDS_SERVER/logs/pid ] 
	    then
		    echo "`$gettext 'removing'` $NDS_SERVER/logs/pid\c"
		    /usr/bin/rm -f $NDS_SERVER/logs/pid
		    echo "`$gettext '...done'`"
	    fi
	    if [ -f $NDS_SERVER/lock ]
	    then
		    echo "`$gettext 'removing'` $NDS_SERVER/lock\c"
		    /usr/bin/rm -f $NDS_SERVER/lock
		    echo "`$gettext '...done'`"
	    fi
	    if [ -f $NDS_SERVER/logs/wdnotify ]
	    then
		    echo "`$gettext 'removing'` $NDS_SERVER/logs/wdnotify\c"
		    /usr/bin/rm -f $NDS_SERVER/logs/wdnotify
		    echo "`$gettext '...done'`"
	    fi

    }

    check_usage() {
	    if [ "$1" -gt "3" ] 
	    then
                echo "`$gettext 'Usage:'` $0 { start | stop | version }"
                exit 1
	    elif [ "$2" != "delete" ]
	    then
	        if [ "$1" -gt "1" ] && [ "$2" != "showlog" ]
                then
                    echo "`$gettext 'Usage:'` $0 {  start | stop | version }"
                    exit 1
                fi
	    elif [ "$1" -gt "2" ] && [ "$3" != "showlog" ]
	    then
                echo "`$gettext 'Usage:'` $0 { start | stop | version }"
	    elif [ "$1" = "1" ]
	    then
                echo "`$gettext 'Usage:'` $0 { start | stop | version }"
	    fi
    }

stop_server() {
#   echo "`$gettext 'stopping auth helpers ... '`"
    stop_helpers
#   echo "`$gettext 'done.'`"
#   echo "`$gettext 'stopping web container instance ... '`"
#   stop_web_container_instance
#   echo "`$gettext 'done.'`"
#   echo "`$gettext 'stopping web server administrator ... '`"
#   stop_ws_instance "$WS_ADMIN" "adm"
#    echo "`$gettext 'done.'`"
#		echo "`$gettext 'stopping directory server ... '`"
#  stop_ds
    }
    
start_server() {
    start_helpers
#   echo "`$gettext 'starting web container instance ... '`"
#   start_web_container_instance
#   echo "`$gettext 'done.'`"
}

start_web_container_instance() {

    $WS_INSTANCE/start
    if [ $? -eq 1 ]; then
        echo "`$gettext 'unable to start'`"
    fi
}

stop_web_container_instance() {

    $WS_INSTANCE/stop
    if [ $? -eq 1 ]; then
        echo "`$gettext 'unable to stop'`"
    fi
}

##############################################################

uninstall_instances() {
   server_deploy_uri="SERVER_DEPLOY_URI"
   console_deploy_uri="CONSOLE_DEPLOY_URI"
   common_uri="COMMON_DEPLOY_URI"
   password_deploy_uri=PASSWORD_DEPLOY_URI
   instance_deleted=0
   cd $PLATFORMBINDIR
   for ams in `ls | grep amserver`; do
      ins=`$ECHO $ams | cut -f2 -d"."`
      if [ "$ins" = "instance_template" ]; then
         continue
      elif [ "$ins" = "" ]; then
         continue
      elif [ "$ins" = "amserver" ]; then
         continue
      elif [ "$1" = "" ]; then
         instance_deleted=1
         ./$ams stop
         delete_server_entry $ins
         # wdeploy -delete instance deployed files
         if [ -d "$PACKAGEDIR/web-apps-$ins/services" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME services for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $server_deploy_uri -i "$ins" -v https-$ins -n hard
         fi

         if [ -d "$PACKAGEDIR/web-apps-$ins/introduction" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME introduction for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $common_uri -i "$ins" -v https-$ins -n hard
         fi

         if [ -d "$PACKAGEDIR/web-apps-$ins/applications/console" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME console for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $console_deploy_uri -i "$ins" -v https-$ins -n hard
         fi
         if [ -d "$PACKAGEDIR/web-apps-$ins/password" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME password for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $password_deploy_uri -i "$ins" -v https-$ins -n hard
         fi

         rm -rf $PACKAGEDIR/web-apps-$ins

         echo "`$gettext 'deleting instance:'` $ins"
         chmod 777 $ams
         rm -f $ams
         rm -rf $PACKAGEDIR/servers/https-$ins
         rm -rf $AMCONF_DIR/AMConfig-$ins.properties
         # delete the acl files
         rm -f $IWS_SERVER_HOME/httpacl/generated.https-$ins.acl
         rm -f $IWS_SERVER_HOME/httpacl/genwork.https-$ins.acl

      elif [ "$ins" = "$1" ]; then
         instance_deleted=1
         delete_server_entry $ins
         ./$ams stop
         echo "`$gettext 'deleting instance:'` $ins"
         # wdeploy -delete instance deployed files
         if [ -d "$PACKAGEDIR/web-apps-$ins/services" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME services for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $server_deploy_uri -i "$ins" -v https-$ins -n hard
         fi

         if [ -d "$PACKAGEDIR/web-apps-$ins/introduction" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME introduction for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $common_uri -i "$ins" -v https-$ins -n hard
         fi

         if [ -d "$PACKAGEDIR/web-apps-$ins/applications/console" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME console for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $console_deploy_uri -i "$ins" -v https-$ins -n hard
         fi
         if [ -d "$PACKAGEDIR/web-apps-$ins/password" ]; then
            eval echo "`$gettext 'wdeploy delete $PRODUCTNAME password for the instance'`: $ins"
            $IWS_SERVER_HOME/bin/https/httpadmin/bin/wdeploy delete -u $password_deploy_uri -i "$ins" -v https-$ins -n hard
         fi

         rm -rf $PACKAGEDIR/web-apps-$ins

         chmod 777 $ams
         rm -f $ams
         rm -rf $PACKAGEDIR/servers/https-$ins
         rm -rf $AMCONF_DIR/AMConfig-$ins.properties
         # delete the acl files
         rm -f $IWS_SERVER_HOME/httpacl/generated.https-$ins.acl
         rm -f $IWS_SERVER_HOME/httpacl/genwork.https-$ins.acl

         rm -f /etc/rc3.d/K55amserver.$ins
         rm -f /etc/rc3.d/S55amserver.$ins
         break
      fi
   done
   if [ "$instance_deleted" = "0" ]; then
      echo "`$gettext 'No instance has been deleted'`"
   else
      echo "`$gettext 'Delete instance completed'`"
   fi
}

###################################
delete_server_entry() {
   instance=$1
   serverhost=`cat $AMCONF_DIR/AMConfig-$instance.properties | grep "com.iplanet.am.server.host" | /usr/bin/awk 'BEGIN { FS = "=" } { print $2 }'`
   serverport=`cat $AMCONF_DIR/AMConfig-$instance.properties | grep "com.iplanet.am.server.port" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
   protocol=`cat $AMCONF_DIR/AMConfig-$instance.properties | grep "com.iplanet.am.server.protocol" | awk ' BEGIN { FS="=" } { print $2 }'`
   server="$protocol://$serverhost:$serverport"
   echo "`$gettext 'deleting server:'` $server"
   CLASSPATH=$PACKAGEDIR/lib/am_sdk.jar:$PACKAGEDIR/lib/am_services.jar:${AMCONF_DIR}:$PACKAGEDIR/lib:$PACKAGEDIR/locale:$JSS_JAR_PATH/jss3.jar:$DSAMELIBDIR/jaas.jar:$JAXP_JAR_PATH/jaxp-api.jar:$JAXP_JAR_PATH/sax.jar:$JAXP_JAR_PATH/xercesImpl.jar:$JAXP_JAR_PATH/dom.jar:$PACKAGEDIR/lib/servlet.jar
   export CLASSPATH
   LD_LIBRARY_PATH=$JSS_JAR_PATH:$NSS_PATH:$NSPR_PATH
   export LD_LIBRARY_PATH
   while [ 1 ]
   do
     $ECHO "`$gettext 'Please enter the amadmin password'`" "\c"
     stty -echo
     read adminpasswd
     stty echo
     if [ "$adminpasswd" = "" ]
     then
      $ECHO "\a `$gettext 'You must enter a password!'`"
      continue
     else
      break
     fi
   done

   ${JDK_BASE_DIR}/bin/java -Djavax.xml.parsers.DocumentBuilderFactory=org/apache/xerces/jaxp/DocumentBuilderFactoryImpl -classpath $CLASSPATH com.iplanet.am.util.AMGenerateServerID delete $server "USER_NAMING_ATTR=amadmin,ou=people,ROOT_SUFFIX" "$adminpasswd"
   #${JDK_BASE_DIR}/bin/java -classpath $CLASSPATH com.iplanet.am.util.AMGenerateServerID delete $server
}

##############################################################################
 
check_amserver_script() {
if [ "$LOCATION" = "/etc/init.d/amserver" ]; then
     exit 1
else
   if [ "$LOCATION" = "./amserver" ] && [ "$PWD" = "/etc/init.d" ]; then
        exit 1
   fi
fi
}

##############################################################

############################################################################

    check_rc_script
    check_usage $# $1 $2
    LOCATION=$0

    # cd out of cdrom dir, so as to make sure no process gets started with
    # cwd = the cdrom, otherwise cdrom can't eject

    cd $IPS_TMP

    umask 022
    AMSERVERHOST=`echo WS61_INSTANCE | sed -e "s/https-//"`
    get_data
    setup_logs $2

    #
    # src utils script
    #
    . "${PLATFORMSHAREDIR}/wsutils.ksh"

    case "$1" in

          'start')
              if [ -f "$WS_INSTANCE/logs/pid" ] || [ -f "$WS_ADMIN/logs/pid" ]; then
	          stop_server
              fi
	      start_server
	      ;;

          'stop')
	      stop_server
	      ;;

          'version')
	      echo ""
	      echo "`$gettext \"Sun Java System Identity Server version 2004Q2\"`"
	      echo ""
	      ;;

      *)
              check_amserver_script
              echo "`$gettext 'Usage:'` $0 { start | stop | version }"
	      ;;

    esac
