#!/bin/sh
# Copyright 10/31/01 Sun Microsystems, Inc. All Rights Reserved.
#pragma ident  "@(#)sm_setup_server.sh	1.51 01/10/31 Sun Microsystems"

#
# Note:  This script is used internally by Sun Enterprise SyMON,
# and is not intended to be called directly by users.
# It should not be modified.
#

set_help_location() {
    new_val="$1"
    loc="$BASEDIR/classes/base/console/cfg/help-server-j.x"
    if [ ! -f $loc ] ; then
	echolog "The Sun Management Center Console help configuration file cannot be found."
	echolog "Please re-install the Sun Management Center Console component"
	echolog ""
	/usr/bin/sleep 2
	exit 1
    fi
    echo "# Copyright 1998 Sun Microsystems, Inc. All Rights Reserved." \
	> $loc
    echo "# url for Sun Management Center help server" \
	>> $loc
    echo "# this url will be postfixed with urls mentioned in symon-help-j.x"\
	>> $loc
    echo "# URL format is of the form http://... or file:/...\n" \
	>> $loc
    echo "detail-help = $new_val" \
	>> $loc
    echolog ""
    echolog 'The base URL has been set to $2' $new_val
}
add_user_to_group() {
#
#  $1 = group name
#  $2 = user name
#
    grpline=`/usr/bin/grep -i "$1" /etc/group`
    if [ $? -ne 0 ] ; then
	echolog ""
	echolog 'Could not find group $2.  You will have to set up' $1
	echolog 'the groups manually.  Please add $3 to group $2.' $1 $2
	echolog ""
	return
    fi

    echo "$grpline" | /usr/bin/grep -i "$2" >/dev/null
    [ $? -eq 0 ] && return 0

    len=`echo "$grpline" | /usr/bin/awk '{print length}'`
    lastc=`echo "$grpline" | /usr/bin/cut -c"$len"`
    if [ "$lastc" = ":" ] ; then
	newline="$grpline$2"
    else
	newline="$grpline,$2"
    fi

    # Make sure that the group name has :: after it
    results=`/usr/bin/sed s/"$grpline"/"$newline"/ /etc/group`
    for each_result in $results
    do
        tmp_key=`/usr/bin/expr $each_result : '\(.*\)::.*'`
        if [ "$tmp_key" = "" ]; then
            tmp_key=`echo $each_result | /usr/bin/cut -d: -f1`
            tmp_value=`/usr/bin/expr $each_result : "$tmp_key:\(.*\)"`
            each_result="$tmp_key::$tmp_value"
        fi
        echo $each_result >> /etc/newgrp.$$
    done

    /usr/bin/mv /etc/newgrp.$$ /etc/group
}

add_group_members() {
#
#  $1 = group to copy users from
#
    userlist=`/usr/bin/grep "^$1" /etc/group | /usr/bin/cut -f4 -d:`
    [ $? -ne 0 ] && return 0

    msg_written=0
    OLDIFS=$IFS
    IFS=,
    for each_user in $userlist
    do
	/usr/bin/id $each_user >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
	    echologverbose 'User $3 in group $2 is not a valid user.  Leaving it out of the esusers file.' $1 $each_user
	    msg_written=1
	    continue
	fi
        /usr/bin/grep "\<$each_user\>" $VARDIR/esusers >/dev/null
	if [ $? -ne 0 ] ; then
	    echologverbose 'Adding user $2 from group $3 to esusers' $each_user $1
	    echo "$each_user" | /usr/bin/cat >> "$VARDIR/esusers"
	    msg_written=1
	fi
    done
    IFS=$OLDIFS
    [ $msg_written -eq 1 ] && echolog ""
}

setup_esusers() {

    /usr/bin/grep "$ESPRIVATEID" ${VARDIR}/esusers >/dev/null 2>&1
    [ $? -ne 0 ] && echo "$ESPRIVATEID" >> ${VARDIR}/esusers

    /usr/bin/grep "$ESPUBLICID" ${VARDIR}/esusers >/dev/null 2>&1
    [ $? -ne 0 ] && echo "$ESPUBLICID" >> ${VARDIR}/esusers

    admusers=`/usr/bin/grep "^esadm" /etc/group | /usr/bin/cut -f4 -d:`
    domusers=`/usr/bin/grep "^esdomadm" /etc/group | /usr/bin/cut -f4 -d:`

    add_group_members esadm
    add_group_members esops
    add_group_members esdomadm

    if [ -n "$admusers" ] && [ -n "$domusers" ] ; then
	echologverbose 'It appears that you already have some users \\\($2\\\)' $admusers
	echologverbose "configured as Sun Management Center administrators.  Leaving these users in place."
	return 0
    fi

    echolog "You should setup a user as a Sun Management Center administrator."
    echolog "This person will be added to the esadm and esdomadm groups."
    get_input_from_user "Please enter a user to be the Sun Management Center administrator: "
    [ "$answer" = "_none_" ] && return 0

    /usr/bin/id "$answer" >/dev/null 2>&1
    while [ $? -ne 0 ]
    do
	echolog ""
	echolog '$2 is not a valid user.' $answer
	get_input_from_user "Please enter a valid username: "
	[ "$answer" = "_none_" ] && return 0
	/usr/bin/id "$answer" >/dev/null 2>&1
    done
    SYM_ADM="$answer"
    /usr/bin/grep -i "$SYM_ADM" ${VARDIR}/esusers >/dev/null 2>&1
    [ $? -ne 0 ] && echo "$SYM_ADM" | /usr/bin/cat >> ${VARDIR}/esusers

    add_user_to_group esadm "$SYM_ADM"
    add_user_to_group esdomadm "$SYM_ADM"
}

create_group() {
    groupname="$1"
    groupid=1000
    gidfound="FALSE"
    GroupIdList=`/usr/bin/cat /etc/group | /usr/bin/cut -f 3 -d :`
    GroupNameList=`/usr/bin/cat /etc/group | /usr/bin/cut -f 1 -d :`
    echo "$GroupNameList" | /usr/bin/grep -w $groupname > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
        #group is already present so go ahead
        echologverbose ""
        echologverbose 'The group $2 already exists on your system.' $1
        echologverbose ""
        return 0
    fi

    echologverbose 'Creating the group $2 that contains Sun Management Center $3 Users.' $1 "$2"
    echologverbose ""
    #echolog "/usr/sbin/groupadd $1"
    #addout=`/usr/sbin/groupadd $1 2>&1`
    # 
    # Check the return value here.
    #
    while [ $gidfound = "FALSE" ]
    do
	 echo "$GroupIdList" | /usr/bin/grep -w $groupid > /dev/null 2>&1
	 if [ $? -eq 0 ] ; then
	     groupid=`/usr/bin/expr $groupid + 1`
	     continue
	 else
	     gidfound="TRUE"
	     echo "$groupname::$groupid:" >> /etc/group
	 fi
    done

}


verify_string() {
#
#  Verifies that a string can be found in a file.
#
# $1 is string to search for
# $2 is file to search
#
    /usr/bin/grep $1 $2 >/dev/null 2>&1
    if [ $? -ne 0 ] ; then
	echologverbose ""
	echologverbose 'Could not find $2 in $3' $1 $2
	echologverbose ""
	exit 1
    fi
}

#########################################
#
fix_ent_vers() {
#
#  Fixes the enterprise and version fields
#
#    echo "\nBefore:\n$LINE"

    LINE=`echo $LINE | /usr/bin/sed s/halcyon/sun/g`
    LINE=`echo $LINE | /usr/bin/sed s/'version *= *\"1\.0\"'/'version = \"2.0\"'/`

}



fix_topology_modules() {

	[ -f $VARDIR/topology-modules-d.dat.old ] && /usr/bin/rm $VARDIR/topology-modules-d.dat.old
	if [ -f $VARDIR/topology-modules-d.dat ]; then
		/usr/bin/mv $VARDIR/topology-modules-d.dat $VARDIR/topology-modules-d.dat.old
		SED=/usr/bin/sed

		while read LINE
		do
			module=`echo $LINE | /usr/bin/awk '{print $1}'`
			case $module in
				domain-control)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.domain\.control/prod.sunsymon.agent.modules.domainControl/g`
					LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.domainControl\"'/`
					;;
				topology-license)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.localApplication\.topology\.license/prod.sunsymon.agent.modules.topologyLicense/g`
					LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.topologyLicense\"'/`
					;;
				topology*)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.topology/prod.sunsymon.agent.modules.topology/g`
					LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.topology\"'/`
					;;
				discovery)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.discovery/prod.sunsymon.agent.modules.discovery/g`
					LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.discovery\"'/`
					;;
				*)
					;;
			esac
			LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
			LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
			#  Remove the first \
			LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
			echo "$LINE" >> $VARDIR/topology-modules-d.dat

		done < "$VARDIR/topology-modules-d.dat.old"

	fi

}



fix_cfgserver_modules() {

	[ -f $VARDIR/cfgserver-modules-d.dat.old ] && /usr/bin/rm $VARDIR/cfgserver-modules-d.dat.old
	if [ -f $VARDIR/cfgserver-modules-d.dat ] ; then
		/usr/bin/mv $VARDIR/cfgserver-modules-d.dat $VARDIR/cfgserver-modules-d.dat.old
		SED=/usr/bin/sed

		while read LINE
		do
			module=`echo $LINE | /usr/bin/awk '{print $1}'`
			case $module in
				cfgserver)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.cfgserver/prod.sunsymon.agent.modules.cfgserver/g`
					LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.cfgserver\"'/`
					;;
				*)
					;;
			esac
			LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
			LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
			#  Remove the first \
			LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
			echo "$LINE" >> $VARDIR/cfgserver-modules-d.dat

		done < "$VARDIR/cfgserver-modules-d.dat.old"

	fi
}



fix_trap_modules() {

	return 0

}



fix_event_modules() {

	[ -f $VARDIR/event-modules-d.dat.old ] && /usr/bin/rm $VARDIR/event-modules-d.dat.old
	if [ -f $VARDIR/event-modules-d.dat ] ; then 
		/usr/bin/mv $VARDIR/event-modules-d.dat $VARDIR/event-modules-d.dat.old
		SED=/usr/bin/sed

		while read LINE
		do
			module=`echo $LINE | /usr/bin/awk '{print $1}'`
			case $module in
				eventmgr)
					fix_ent_vers
					LINE=`echo $LINE | $SED s/primealert\.modules\.localApplication\.eventmgr/prod.sunsymon.agent.modules.eventmgr/g`
					LINE=`echo $LINE | $SED s/'location = ""'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.eventmgr\"'/`
					;;
				*)
					;;
			esac
			LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
			LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
			#  Remove the first \
			LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
			echo "$LINE" >> $VARDIR/event-modules-d.dat

		done < "$VARDIR/event-modules-d.dat.old"

	fi
}

fix_cstservice_modules() {

	return 0

}

# Input: $1 default lookup_service port
#
#
check_lookup_service_port() {
   service_port="$1"
   /usr/bin/netstat -an | /usr/bin/grep "\*\.$1 " >/dev/null
   if [ $? -eq 0 ] ; then
      echolog ''
      echolog "------------------------  WARNING  ------------------------"
      echolog 'It appears that $2 $3 is already in use.' "lookup service port" "$service_port"
      echolog 'Sun Management Center $2 may not be able to run due to this conflict.' "lookup service"
      echolog "There are two ways to correct this conflict:"
      echolog "  1. Reconfigure the port that Sun Management Center uses."
      echolog "  2. Stop the process that is using the port."
    
      retcode=1
      while [ $retcode -ne 0 ]; do
         echolog 'Hit ENTER key to force default port.'
         get_input_from_user "Please enter port you would like to use [ 1100 to 65535 ]:"
         
         if [ -z "$answer" ]; then
            echolog ''
            echolog 'NOTE: Prior to starting Sun Management Center $2, stop the process using port $3.' "lookup service" "$service_port"
            answer="$1" && break
         fi
         
         /usr/bin/expr $answer + 1  1> /dev/null  2>&1 
         retcode=$?
         if [ $retcode -ne 0 ] ; then
            echolog 'Port $2 is not a valid port number, Please try again.' "$answer"
            continue
         fi

         if [ $answer -lt 1100 -o $answer -gt 65535 ] ; then
            echolog 'Invalid port. Please try again.'
            retcode=1
            continue
         fi         
 
         /usr/bin/netstat -an | /usr/bin/grep "\*\.$answer " >/dev/null
         retcode=$?
         [ $retcode -gt 0 ] && break
         echolog 'The port you entered is busy. Please try again.'
      done
      service_port="$answer"
    fi
    
}


######################################################
#
#  Main entry point
#
prog_base=`/usr/bin/basename $0`
common_cmd=`echo $0 | /usr/bin/sed s/$prog_base/es-common.sh/`
. $common_cmd
gen_cmd=`echo $0 | /usr/bin/sed s/$prog_base/es-keys.sh/`
. $gen_cmd

VERBOSE=OFF
do_default=0
while getopts dvs: OPT
do
    case $OPT in
	d)
	    do_default=1
	    ;;
	v)
	    VERBOSE=ON
	    ;;
        s)
            security_seed="$OPTARG"
            #echologverbose 'Using security seed $2 for Sun Management Center server' "$security_seed"
            ;;

	*)
	    exit 1
    esac
done
set_basedir

PROGNAME="$0"; export PROGNAME
check_root
check_logfile setup

check_osver
set_xput

echologverbose ""
echologverbose "This part of the setup process does the Sun Management Center Server Component setup."

#
#  Create the necessary user groups (if needed)
#
create_group esadm Admin
create_group esdomadm "Domain Admin"
create_group esops Operator

setup_esusers
#
#  Create the backgrounds directory
#
[ ! -d "$VARDIR/backgrounds" ] && /usr/bin/mkdir "$VARDIR/backgrounds"
/usr/bin/cp -r "$BASEDIR/classes/base/console/cfg/backgrounds" "$VARDIR"

current_host=`/usr/bin/hostname`

#
#  Setup domain-config.x
#
#  First check the settings used by Agent Component
#
agent_port=""
platform_port=""
if [ -f ${VARDIR}/domain-config.x ] ; then
    agent_port=`$XGET ${VARDIR}/domain-config.x agent.snmpPort`
    platform_port=`$XGET ${VARDIR}/domain-config.x platform.snmpPort`
fi

$XPUT "${VARDIR}/domain-config.x" agent.agentServer "$current_host" \
	trap.trapServer "$current_host" event.eventServer "$current_host" \
	platform.platformServer "$current_host" 

if [ -z "$agent_port" ] ; then
    $XPUT "${VARDIR}/domain-config.x" \
	agent.snmpPort 161 trap.snmpPort 162 event.snmpPort 163 metadata.snmpPort 168
    if [ $? -ne 0 ] ; then
	echolog ""
	echolog 'Unable to set $2 values.' "$VARDIR/domain-config.x"
	echolog ""
	exit 1
    fi
else
    echologverbose ""
    echologverbose 'agent.snmpPort is already configured in $2' "$VARDIR/domain-config.x"
    echologverbose ""
fi

[ -z "$platform_port" ] && \
    $XPUT "${VARDIR}/domain-config.x" platform.snmpPort 166

#
#  Now check the settings used by Server Component
#
topo_port=`$XGET ${VARDIR}/domain-config.x topology.snmpPort`
$XPUT "${VARDIR}/domain-config.x" topology.topologyServer "$current_host" \
    cfgserver.cfgserverServer "$current_host" cstservice.cstserviceServer "$current_host"

if [ -z "$topo_port" ] ; then
    $XPUT "${VARDIR}/domain-config.x" \
	topology.snmpPort 164 cfgserver.snmpPort 165 cstservice.snmpPort 167 

    if [ $? -ne 0 ] ; then
	echolog ""
	echolog 'Unable to set $2/domain-config.x values.' $VARDIR
	echolog ""
	exit 1
    fi
else
    echologverbose ""
    echologverbose 'topology.snmpPort is already configured in $2' "$VARDIR//domain-config.x"
    echologverbose ""

fi
check_port topology.snmpPort topology
check_port cfgserver.snmpPort cfgserver
check_port event.snmpPort event
check_port cstservice.snmpPort cstservice
check_port trap.snmpPort trap

#
#  Setup server-config.x
#
if [ ! -f ${VARDIR}/server-config.x ] ; then
    /usr/bin/cp "$BASEDIR"/classes/base/server/cfg/server-config.x \
	${VARDIR}/server-config.x
    # /usr/bin/chmod u+w ${VARDIR}/server-config.x
fi

port=2099
grpout=`/usr/bin/grep rmiPort $VARDIR/server-config.x`
if [ $? -eq 0 ] ; then
    grpout=`echo $grpout`  # remove leading spaces if any
    CH=`/usr/bin/expr "$grpout" : '\(.\).*'`
    if [ "$CH" != "#" ] ; then
	port=`echo "$grpout" | /usr/bin/cut -f2 -d=`
	port=`echo $port`
    fi
fi
check_port_number rmiReceptor.rmiPort server

[ -f "$VARDIR/cfgserver-oids-d.dat" ] && /usr/bin/rm "$VARDIR/cfgserver-oids-d.dat"
[ -f "$VARDIR/event-oids-d.dat" ] && /usr/bin/rm "$VARDIR/event-oids-d.dat"
[ -f "$VARDIR/cstservice-oids-d.dat" ] && /usr/bin/rm "$VARDIR/cstservice-oids-d.dat"
[ -f "$VARDIR/topology-oids-d.dat" ] && /usr/bin/rm "$VARDIR/topology-oids-d.dat"
[ -f "$VARDIR/trap-oids-d.dat" ] && /usr/bin/rm "$VARDIR/trap-oids-d.dat"


# generate seeds only if user is not doing an upgrade

if [ "$UPGRADE_DONE" != "YES"  -a "$GENERATE_SECURITY_KEY" = "1" ]
then
    generate_keys server $do_default "$security_seed"
fi

fix_topology_modules
fix_cfgserver_modules
fix_trap_modules
fix_event_modules
fix_cstservice_modules

echolog "The Sun Management Center base URL is relative to the Sun Management Center Console."
echolog "The Sun Management Center Console is able to request help documentation via the network."
echolog "If you have installed Sun Management Center help documentation in an http-accessible"
echolog "location within your network, you may specify this location."
echolog "If Sun Management Center help is installed on the console host, simply accept the default value."
if [ $do_default -eq 0 ]; then
    get_input_from_user "Please enter base URL to Sun Management Center help [local]: "
else
    answer=""
fi

if [ "$answer" != "" ] ; then
    set_help_location $answer
else
    set_help_location "file:$ESROOT/lib/locale"
fi

#
# copy ServerOverrideBundle.properties files to /var$BASEDIR/classes
#
if [ -f $BASEDIR/classes/ServerOverrideBundle.properties ] ; then
    [ ! -d $VAROPTDIR/classes ] && /bin/mkdir $VAROPTDIR/classes
    /usr/bin/cp $BASEDIR/classes/ServerOverrideBundle* $VAROPTDIR/classes
fi

#
#  Setup host-apps-j.x
#
if [ ! -f ${VARDIR}/host-apps-j.x ] ; then
	/usr/bin/touch ${VARDIR}/host-apps-j.x 
	/usr/bin/chmod u+w ${VARDIR}/host-apps-j.x 
fi


# Check for lookup_service_port & put it in javaserver.properties files
# sets service_port
#
service_port="5600"
check_lookup_service_port "$service_port"

#  Setup javaserver.properties
#
if [ -f $BASEDIR/classes/base/server/cfg/javaserver.properties ] ; then
   [ ! -d $VAROPTDIR/cfg ] && /bin/mkdir $VAROPTDIR/cfg
   [ -f ${VAROPTDIR}/cfg/javaserver.properties ] && /usr/bin/mv -f ${VAROPTDIR}/cfg/javaserver.properties ${VAROPTDIR}/cfg/javaserver.properties.old
   /usr/bin/cp $BASEDIR/classes/base/server/cfg/javaserver.properties /tmp/javaserver.properties
   /usr/bin/cat /tmp/javaserver.properties | /usr/bin/grep -v "ServiceRegistryPort" > ${VAROPTDIR}/cfg/javaserver.properties
   /usr/bin/echo  "ServiceRegistryPort = $service_port\n" >> ${VAROPTDIR}/cfg/javaserver.properties
   /usr/bin/rm -f /tmp/javaserver.properties
fi

#  Setup javaservice.properties
#
if [ -f $BASEDIR/classes/base/server/cfg/javaservice.properties ] ; then
   [ ! -d $VAROPTDIR/cfg ] && /bin/mkdir $VAROPTDIR/cfg
   [ -f ${VAROPTDIR}/cfg/javaservice.properties ] && /usr/bin/mv -f ${VAROPTDIR}/cfg/javaservice.properties ${VAROPTDIR}/cfg/javaservice.properties.old
   /usr/bin/cp $BASEDIR/classes/base/server/cfg/javaservice.properties /tmp/javaservice.properties
   /usr/bin/cat /tmp/javaservice.properties | /usr/bin/grep -v "ServiceRegistryPort"  > ${VAROPTDIR}/cfg/javaservice.properties
   /usr/bin/echo  "ServiceRegistryPort = $service_port\n" >> ${VAROPTDIR}/cfg/javaservice.properties
   /usr/bin/rm -f /tmp/javaservice.properties
fi

#  Setup server-ddl.properties
#
if [ -f $BASEDIR/classes/base/server/cfg/server-ddl.properties ] ; then
    [ ! -d $VAROPTDIR/cfg ] && /bin/mkdir $VAROPTDIR/cfg
    /usr/bin/cp $BASEDIR/classes/base/server/cfg/server-ddl.properties $VAROPTDIR/cfg
    /usr/bin/chmod u+w ${VAROPTDIR}/cfg/server-ddl.properties
fi

echologverbose ""
echologverbose "Completing Sun Management Center Server Component setup."
echologverbose ""

exit 0

