#!/bin/sh
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#ident        "@(#)adminserver        1.6 - 02/02/20"
# set -x

#########################################
# plaformDependent_subcommand_usage 
# print subcommand usage message
# input: $1 - type of the subcommand
# 	 $2 - directory of the subcommand
#########################################
platformDependent_subcommand_usage () {
COMMAND=$1 # subcommand
DIR=$2

case "$COMMAND" in

sync-cds )
	echo "Usage: $COMMAND [5.2] [-f {absolute path to credentials file}] "
	;;
* )
	usage 0
	;;
esac
}

##########################################
# platformDependent_usage
#
##########################################
platformDependent_usage () {
	echo "Usage: ${ASCMD}"
	echo "	   { sync-cds } [5.2] [-f {absolute path to credentials file}] "
	return 0
}

##########################################
# set_env_vars
#
##########################################
set_env_vars () {
   pkg_get_basedir SUNWasvu
   AS_BASEDIR=$BASEDIR
   USR_ADM=$AS_BASEDIR/usr/sadm/mps/admin/v5.2
   ETC_ADM=$AS_BASEDIR/etc/mps/admin/v5.2

   VAR_ADM=$AS_BASEDIR/var/mps/serverroot
   if [ -f $ETC_ADM/shared/config/serverroot.conf ]; then
      VAR_ADM=`cat $ETC_ADM/shared/config/serverroot.conf`
   fi

   USR_ADM_PUBLIC=$AS_BASEDIR/usr/sbin

   AS_SETUP_DIR=$AS_BASEDIR/usr/lib/mps/admin/setup

   pkg_get_java_dir
   JRE_DIR=$J2SEDIR/jre
   JAVA=$J2SEDIR/bin/java

   JAVA_HOME=$JRE_DIR; export JAVA_HOME;

   PERLCMD=/usr/bin/perl
   LD_LIBRARY_PATH=$USR_ADM/lib:$LD_LIBRARY_PATH; export LD_LIBRARY_PATH

}

##########################################
# exec_no_unconfigure_found
#
##########################################
exec_no_unconfigure_found () {

    # if we are in an HA case, second node unconfiguration, some cleaning
    # must be performed on the current node.
    if [ -f $ETC_ADM/shared/config/serverroot.conf ] && [ ! -f $VAR_ADM/admin-serv/config/adm.conf ]; then
      exec_ha_unconfigure_subcommand
      return $?
    fi

}

##########################################
# exec_ha_unconfigure_subcommand
#
# pre-condition : serverroot.conf exists and 
#admin server uninstaller has been removed.
#
##########################################
exec_ha_unconfigure_subcommand () {
  echo "Removing remaining files..."
  ERROR=0

  # removing serverroot.conf only if the server root dir does not exist anymore
  # or if no product can be unconfigured from it.
  if [ ! -d ${VAR_ADM} ] || [ ! -f ${VAR_ADM}/setup/uninstall_*.class ]; then
    echo "Finishing unconfiguration of Administration Server 5.2 for this cluster node."
    rm ${AS_BASEDIR}/etc/mps/admin/v5.2/shared/config/serverroot.conf
    if [ $? -ne 0 ]; then
	echo "Cannot remove ${AS_BASEDIR}/etc/mps/admin/v5.2/shared/config/serverroot.conf. Try manually." 	
	ERROR=1 
    fi
  fi

  return $ERROR
}

#########################################
# getPkgBase
#
##########################################

getPkgBase () {
    pkginfo -r $1 2> /dev/null
}


#########################################
# getMultiplePkgInfo
#
##########################################

getMultiplePkgInfo () {
    pkginfo "$1.*"
}


#########################################
# getPkgRev
#
##########################################

getPkgRev () {
    pkginfo -x $1
}


#########################################
# getPkgList
#
# NSPR (SUNWpr)
# NSS  (SUNWtls)
# ICU  (SUNWicu)
# LDAP (SUNWldk)
# SASL (SUNWsasl)
# JSS  (SUNWjss)
#
##########################################

getPkgList () {
    PKGS="
	SUNWpr 
	SUNWtls
	SUNWicu
	SUNWldk
	SUNWsasl
	SUNWjss
	SUNWasvr
    "
}


#########################################
# getAdmServPkgList
#
#
##########################################
getAdmServPkgList () {
    PKGS="
	SUNWasvc 
	SUNWasvcp
	SUNWasvu
    "
}

#########################################
# pkg_get_java_dir
#
# set BASEDIR variable 
##########################################
pkg_get_java_dir () {
    # Locate Orion installed J2SE package
    if [ -h /usr/jdk/entsys-j2se ]; then
    	J2SEDIR=/usr/jdk/entsys-j2se
	return 0
    fi

    # Use default J2SE
    pkg_get_basedir SUNWj3rt
    if [ $? -ne 0 ]; then
    	return $?
    fi
    J2SEDIR=$BASEDIR/j2se
    return 0
  	
}

#########################################
# getBuildNumber52
#
# set buildNumber52 variable
# on sparc:
# RTM 5.2 buildNumber: 2003.142.1411
# OR1 5.2 buildNumber: 2003.275.1918
#
# on i386:
# RTM 5.2 buildNumber: 2003.142.1439
# OR1 5.2 buildNumber: 2003.275.1947
#
##########################################
getBuildNumber52 () {
  
# if revision 1 (115610-01 or 115611-01) has been applied,
# we assume that be back to 5.2 means be back to OR1 delivery.
# if it is not the case, it means that RTM has been installed on the system.

    if [ `uname -p` = "sparc" ]; then
	buildNumber52="2003.142.1411"
	(showrev -p | grep 115610-01) 2>&1 > /dev/null
	if [ $? -eq 0 ]; then
	    buildNumber52="2003.275.1918"
	fi
    else
	if [ `uname -p` = "i386" ]; then
	    buildNumber52="2003.142.1439"
	    (showrev -p | grep 115611-01) 2>&1 > /dev/null
	    if [ $? -eq 0 ]; then
		buildNumber52="2003.275.1947"
	    fi
	fi
    fi
}




##########################################
# exec_synccds_subcommand
#
# input: "$@" of the adminserver
# return: 0 - success
#         None zero - Fail
#########################################
exec_synccds_subcommand () {

OPTIONS="-r $VAR_ADM "

# check if '5.2' option has been specified

 shift

 if [ $# -ne 0 ] && [ $1 = "5.2" ]; then
    OPTIONS="$OPTIONS -v 5.2 -j admserv52.jar -n \"Administration Server\""
    getBuildNumber52
    if [ "x$buildNumber52" != x ]; then
       OPTIONS="$OPTIONS -b $buildNumber52"
    fi
        
    shift
 fi

 # read the options

 while getopts f: LOPT
     do
       case $LOPT in
          f)   
		OPTIONS="$OPTIONS -$LOPT $OPTARG"
		shift
		shift
		;;         
          \?)     
             	;;
          esac
 done

 # if there is still an argument not evaluated, it is a non valid case
 if [ $# -ne 0 ]; then 
    subcommand_usage sync-cds
    return 1
 fi

 # run the command to sync the admin
 cd $VAR_ADM/bin/admin/
 eval ./sync-admin-cds $OPTIONS		
 sync_admin_cds_status=$?
 
 return $?

}


##########################################
# platformDependent_subcommand
#
# input: "$@" of the adminserver
#########################################
platformDependent_subcommand () {

case "$1" in
* )
	usage 1
	;;
esac
}
#########################################
# usage
# print usage message
# input: $1 - 1: exit 1
#             0: do not exit
#########################################
usage () {
	echo "Usage: $ASCMD"
	echo "	   help [ subcommand ]"
	echo "Usage: $ASCMD "
	echo "	   configure [ -f <configuration file> ]"
	echo "Usage: $ASCMD "
	echo "	   unconfigure [ -f <unconfiguration file> ] "
	echo "Usage: $ASCMD "
	echo "	   { start | stop | restart | startconsole }"
	echo "Usage: $ASCMD "
	echo "	   { sagt | magt } { options-and-arguments ...}"
	echo "Usage: ${ASCMD}"
	echo "	   { admin_ip } { options-and-arguments ...}"
	platformDependent_usage
	echo "  where options-and-arguments depend on the specific subcommand"
	[ $1 -eq 1 ] && exit 1
}
#########################################
# subcommand_usage 
# print subcommand usage message
# input: $1 - type of the subcommand
# 	 $2 - directory of the subcommand
#########################################
subcommand_usage () {
COMMAND=$1 # subcommand
DIR=$2

case "$COMMAND" in

help )
	usage 1
	;;
configure )
	echo "Usage: $COMMAND [ -f <configuration file> ]"
	;;

unconfigure )
	echo "Usage: $COMMAND [ -f <unconfiguration file> ] "
	;;
start | \
stop  | \
restart | \
startconsole  )
 	echo "Usage: $COMMAND "
	;;
sagt | \
magt )
	CMD_HELP=`$USR_ADM/plugins/snmp/$COMMAND/$COMMAND --help 2>&1 1>/dev/null`
	PARAM=`echo $CMD_HELP | sed 's,^Usage: [^         ]* ,,'`
	echo "Usage: $COMMAND $PARAM "
	;;
admin_ip )
	ADMIN_IP_HELP=`$PERLCMD $USR_ADM/shared/bin/$COMMAND.pl 2>&1 1>/dev/null`
	PARAM=`echo $ADMIN_IP_HELP | sed 's,^Usage: [^         ]* ,,'`
	echo "Usage: $COMMAND $PARAM "
        ;;
* )
	platformDependent_subcommand_usage $1 $2
	;;
esac
exit 0
}

##########################################
# exec_usr_subcommand
#
# input: parameters of mpsadmserver
# return: the return code of the subcommand
##########################################
exec_usr_subcommand () {

COMMAND=$1 # subcommand

# Skip subcommand.
# The $@ become the parameters for
# the subcommand
shift

case "$COMMAND" in
admin_ip )
	$PERLCMD $USR_ADM/shared/bin/admin_ip.pl "$@"
	;;
* )
	usage 0
	return 1
esac

return $?
}


##########################################
# is_root
#
# return: 1 - TRUE
#         0 - FALSE
##########################################
is_root () {
ROOTID=`id | grep "uid=0(root)"`
if [ -z "$ROOTID" ]; then
  return 0
else
  return 1
fi
}

##########################################
# exec_new_configure_subcommand
#
##########################################
exec_new_configure_subcommand () {

# check packages are installed correctly
as_pkg_check
if [ $? -ne 0 ]; then
    exit 1
fi


OPTIONS=
# Handle silent install (-f configfile)
if [ "(" $# -eq 2 ")" -a "(" "$1" = "-f" ")" ]; then
    statefile=$2
    # Make sure we have an absolute path to the file before we cd 
    if [ ! "(" `echo $statefile | cut -c1` = "/" ")" ]; then
	statefile=`pwd`/$statefile
    fi
    OPTIONS="-nodisplay -noconsole -state $statefile"
else
    OPTIONS=$@
fi

if [ -f $USR_ADM/setup/SunONEAdministrationServer52.class ]; then
    cd $USR_ADM   
    $JAVA -cp ./setup -Djava.library.path=$AS_SETUP_DIR SunONEAdministrationServer52 $OPTIONS
    return $?
else 
    echo "Configuration program cannot be found."
    exit 1
fi


}
##########################################
# exec_configure_subcommand
#
##########################################
exec_configure_subcommand () {
shift # skip "configure" in $1


# check JRE to be able to run the installer
java_check 

exec_new_configure_subcommand "$@"
return $?

}

##########################################
# exec_new_unconfigure_subcommand
#
##########################################
exec_new_unconfigure_subcommand () {

OPTIONS=
# Handle silent install (-f configfile)
if [ "(" $# -eq 2 ")" -a "(" "$1" = "-f" ")" ]; then
    statefile=$2
# Make sure we have an absolute path to the file before we cd 
if [ ! "(" `echo $statefile | cut -c1` = "/" ")" ]; then
    statefile=`pwd`/$statefile
fi
OPTIONS="-nodisplay -noconsole -state $statefile"
    else
OPTIONS=$@
fi

UNINSTALL_CLASS=uninstall_Sun_ONE_Administration_Distribution
if [ -f $VAR_ADM/setup/${UNINSTALL_CLASS}.class ]; then
    cd $USR_ADM
    $JAVA -cp $VAR_ADM/setup:$USR_ADM/setup -Djava.library.path=$AS_SETUP_DIR ${UNINSTALL_CLASS} $OPTIONS
    return $?
else 
    #
    #
    exec_no_unconfigure_found
    if [ $? -eq 0 ]; then
      return 0
    else
      echo "Unconfiguration program cannot be found."
      echo "You must configure Administration Server before running ${USR_ADM_PUBLIC}/mpsadmserver unconfigure."
      echo "Run ${USR_ADM_PUBLIC}/mpsadmserver configure."
      exit 1
    fi
fi

}

##########################################
# exec_unconfigure_subcommand
#
##########################################
exec_unconfigure_subcommand () {

shift # skip "unconfigure" in $1


# check JRE to be able to run the installer
java_check 

exec_new_unconfigure_subcommand "$@"
return $?

}
##########################################
# exec_admin_subcommand
#
# input: "$@" of the adminserver
# return: 0 - success
#         None zero - Fail
#########################################
exec_admin_subcommand () {
COMMAND=$1
case "$COMMAND" in
start | \
stop  | \
restart )
	COMMAND=$COMMAND-admin
	if [ $# -ne 1 ]; then
		echo "Usage: $ASCMD $COMMAND"
		return 1
	fi

	WHOAMI=`id | sed 's,uid=[0-9]*(,,' | sed 's,).*,,'`
	is_root
	IS_ROOT=$?
        if [ $IS_ROOT -eq 0 ]; then
	    ISOWNERFILE=`find $VAR_ADM/$COMMAND -user $WHOAMI | wc -l`
	    OWNERFILE=`ls -ld $VAR_ADM/$COMMAND | sed 's,..........[ ]*[0-9]* ,,' | sed 's, .*,,'`
	    if [ $OWNERFILE = "root" ]; then
	       echo "You must be root to run this command."
	       exit 1
	    fi
	    if [ $ISOWNERFILE -eq 0 ]; then	     
	      echo "You must be $OWNERFILE or root to run this command."
	      exit 1
	    fi
	fi

	sh $VAR_ADM/$COMMAND
	rc=$?
	if [ $IS_ROOT -eq 0 ]; then
	  if [ $COMMAND = "stop-admin" ]; then
	    if [ $rc -eq 1 ]; then
	      echo "Cannot stop the Administration Server as $WHOAMI."
	      echo "Run ${USR_ADM_PUBLIC}/mpsadmserver stop as root."
	    fi
	  fi
	fi

	return $rc
	;;
startconsole )
	shift
	while getopts ":l:" LOPT
	do
        	[ "$LOPT" = "l" ] && break
	done
	if [ "$LOPT" != "l" ] && [ ! -z "$LANG" ]; then
		LOPT=`echo $LANG | awk '
			/^zh$/ || /^zh\..*/ || /^zh_CN.*/ { print "-l zh"}
			/^ja.*/ {print "-l ja"}'`
	else
        	LOPT=
	fi

	$USR_ADM_PUBLIC/mpsconsole "$@" $LOPT
	return $?
	;;
* )
	usage 0
	return 1
	;;
esac	

}
##########################################
# exec_snmp_subcommand
#
# input: "$@" of the adminserver
# return: 0 - success
#         None zero - Fail
#########################################
exec_snmp_subcommand () {

COMMAND=$1
if [ "$COMMAND" = "magt" ]; then

	WHOAMI=`id | sed 's,uid=[0-9]*(,,' | sed 's,).*,,'`
	is_root
	IS_ROOT=$?
        if [ $IS_ROOT -eq 0 ]; then
	    ISOWNERFILE=`find $VAR_ADM/plugins/snmp/$COMMAND/$COMMAND -user $WHOAMI | wc -l`
	    OWNERFILE=`ls -ld $VAR_ADM/plugins/snmp/$COMMAND/$COMMAND | sed 's,..........[ ]*[0-9]* ,,' | sed 's, .*,,'`
	    if [ $ISOWNERFILE -eq 0 ]; then	     
	      echo "You must be $OWNERFILE or root to run this command."
	      exit 1
	    fi
	fi

	PID_FILE=$VAR_ADM/admin-serv/logs/pid_masteragt
	PID=0
	if [ -f $PID_FILE ]; then
	  PID=`cat $PID_FILE 2> /dev/null`
	fi
	if [ $PID -ne 0 ]
	then
	  if kill -0 $PID >/dev/null 2>&1 ; then
	        echo "The MPS agent is already running (pid $PID)."
	        return 1
	  else
	        rm -f $PID_FILE
	  fi
	fi
	echo "$$" >$PID_FILE

fi

shift

#
# For integration with Solaris master agent.
# Silently exec the agent.
#
cd $VAR_ADM/plugins/snmp/$COMMAND
exec $VAR_ADM/plugins/snmp/$COMMAND/$COMMAND "$@"
}




#########################################
# java_check
#
# Check for good JRE
#
# S8U4 is the first S8 release to bundle
# the minimum required by setupsdk5
#
##########################################
java_check () {
	$JAVA -fullversion 2>&1| egrep "(1.4.[1-9]|1.5.[0-9])" >/dev/null
	if [ $? -ne 0 ]; then
		echo "WARNING: Need a JRE 1.4.1 or later; ${JAVA} is:"
		$JAVA -fullversion 2>&1
		echo
    fi
}

#########################################
# pkg_print_instances
#
# $1 pkg name
#
##########################################
pkg_print_instances () {
    pkg=$1
    instances=`getMultiplePkgInfo "${pkg}" | awk '{ print $2; }'`
    for n in $instances; do
    revision=`getPkgRev $n | tail -1 | awk '{ print $2 }'`
    basedir=`getPkgBase $n`
    echo "$n\n\t$revision\t$basedir"
    done
}

#########################################
# pkg_check
#
# check that required packages are
# correctly installed :
#
##########################################

pkg_check () {

    rc=0

    getPkgList
    
    basedirs=""

    missing=""
    for pkg in ${PKGS}; do
	num=`getPkgBase "${pkg}" | sort | uniq | wc -l`
	if [ $num -eq 0 ]; then
	    missing="$missing$pkg "
	    continue
	fi
    done

    # check for missing required packages
    if [ -n "$missing" ]; then
	echo "Error: The following packages are not installed:"
	echo $missing
	echo
	rc=1
    fi

	if [ $rc -eq 0 ]; then
		full_list="${PKGS}"
		for pkg in ${full_list}; do
			pkg_check_uniq ${pkg}
			if [ $? -ne 0 ]; then
				rc=1
			fi
		done
	fi

    return $rc
}
 

#########################################
# pkg_check_uniq
##########################################
pkg_check_uniq () {
    pkg=$1
    rc=0
    num=`getMultiplePkgInfo "${pkg}" | wc -l`
    if [ $num -ne 1 ]; then
        echo "WARNING: Package ${pkg} has multiple instances:"
        pkg_print_instances ${pkg}
        echo "WARNING: only ${pkg} is used by Administration Server 5.2"
        rc=1
    fi
    return $rc
}    


#########################################
# as_pkg_check
#
# check that required packages are
# correctly installed
#
##########################################
as_pkg_check () {
    rc=0

    getAdmServPkgList
    
    basedirs=""

    missing=""
    for pkg in ${PKGS}; do
	num=`getMultiplePkgInfo "${pkg}" | sort | uniq | wc -l`
	if [ $num -eq 0 ]; then
	    missing="$missing$pkg "
	    continue
	fi
	instances=`getMultiplePkgInfo "$pkg" | awk '{ print $2; }'`
	for n in $instances; do
	    basedir=`getPkgBase $n`
	    if [ -z "$basedirs" ]; then
		basedirs=$basedir
	    else
		basedirs="$basedirs\n$basedir"
	    fi
	done
    done

    # check for missing required packages
    if [ -n "$missing" ]; then
	echo "Error: The following packages are not installed:"
	echo $missing
	echo
	rc=1
    fi
 
    # check for unique basedir
    num=`echo $basedirs | sort | uniq | wc -l`
    if [ $num -ne 1 ]; then
	echo "Error: The installed packages do not have a unique basedir."
	echo
	rc=1
    fi

    full_list="${PKGS}"
    for pkg in ${full_list}; do
        pkg_check_uniq ${pkg}
        if [ $? -ne 0 ]; then
            rc=1
        fi
    done

    return $rc
}

#########################################
# pkg_get_basedir
#
# set BASEDIR variable 
##########################################
pkg_get_basedir () {
    pkg=$1
    num=`getPkgBase "${pkg}" | sort | uniq | wc -l`
    if [ $num -eq 0 ]; then
	echo "Error: Package ${pkg} is not installed"
	return 1
    fi
    BASEDIR=`getPkgBase "${pkg}" | head -1`
	return 0
}


#########################################
# is_configured 
#
# return non-zero if configuration has been done
#
##########################################
is_configured () {

    if [ -f $VAR_ADM/admin-serv/config/adm.conf ]; then
	return 1
    fi
    return 0
}


#########################################
# exit_if_not_configured 
#
# exit if the configuration has not been done
# if $1="testHA", we also check if
# serverroot.conf file does not exist
# (HA case - unconfiguration of a second node case)
#
##########################################
exit_if_not_configured () {

    is_configured
    if [ $? -eq 0 ]; then
	if [ "$1" != "testHA" ] || [ ! -f $ETC_ADM/shared/config/serverroot.conf ]; then
	echo "You must configure Administration Server first."
	echo "Run ${USR_ADM_PUBLIC}/mpsadmserver configure."
	exit 1
	fi
    fi

}


#########################################
# main 
##########################################

ASCMD=`basename $0`

# Check other packages

# check packages are installed correctly
# no need to check for unconfigure
if [ "x$1" != x ]; then
    if [ $1 != "unconfigure" ]; then
		pkg_check
		if [ $? -ne 0 ]; then
			exit 1
		fi
                # Remove the security check as it is to Orion to take care of this
                #security_check_all 
		#if [ $? -ne 0 ]; then
		#	exit 1
		#fi
	fi
else
	usage 1
fi

set_env_vars

is_root
IS_ROOT=$?
if [ $IS_ROOT -eq 0 ]; then
   case "$1" in 
       help | \
       startconsole )
	    ;;
       configure | \
       unconfigure ) 
            echo "You must be root to run this command."
            exit 1
	    ;;
       * )
	;;
   esac 
fi

case "$1" in
configure )
	# checking required Admin server packages
	as_pkg_check
	if [ $? -ne 0 ]; then
	    exit 1
	fi
	exec_configure_subcommand "$@"
	exit $?
	;;
unconfigure )
	exit_if_not_configured "testHA"
	exec_unconfigure_subcommand "$@"
	exit $?
	;;
start | \
stop  | \
restart | \
startconsole  )
	exit_if_not_configured
 	exec_admin_subcommand "$@"
	exit $?
	;;
admin_ip)
	exit_if_not_configured
	exec_usr_subcommand "$@"
	exit $?
	;;
magt | \
sagt )
	#
	# For integration with Solaris master agent startup.
	# Silence when not configured.
	#
	is_configured
	[ $? -ne 0 ] || exit 1
	exec_snmp_subcommand "$@"
	exit $?
	;;
sync-cds )
	exit_if_not_configured
	exec_synccds_subcommand "$@"
	exit $?
	;;
help )
	shift
	if [ $# -ne 0 ] ; then
		COMMAND="$1"
		HDIR=""	
		subcommand_usage "$COMMAND" "$HDIR"
	else
		usage 1
	fi
	;;
* )
	platformDependent_subcommand "$@"
	;;
esac
