#!/bin/sh
#/*****************************************************************************
#*
#*      (C) Copyright 1989-2003 Trend Micro, Inc.
#*      All Rights Reserved.
#*
#*      This program is an unpublished copyrighted work which is proprietary
#*      to Trend Micro, Inc. and contains confidential information that is not
#*      to be reproduced or disclosed to any other person or entity without
#*      prior written consent from Trend Micro, Inc. in each and every instance.
#*
#*      WARNING:  Unauthorized reproduction of this program as well as
#*      unauthorized preparation of derivative works based upon the
#*      program or distribution of copies by sale, rental, lease or
#*      lending are violations of federal copyright laws and state trade
#*      secret laws, punishable by civil and criminal penalties.
#*
#*-----------------------------------------------------------------------------
#* Title: install script Control Manager agent for ScanMail for Lotus Notes 2.6
#******************************************************************************/

umask 022

# Default
TM_DEFAULT_PATH="/opt/trend"
TMI_DEFAULT_PATH=/opt/trend/TMI
SMLN_DEFAULT_PATH="/opt/trend/SMLN"
TM_INSTALLDIR=$TM_DEFAULT_PATH
SMLN_INSTALLDIR=""
AGENTPKG="CM_Agent.tar"
AGENTPKG_DIR="/etc/smln"
AGENTPKG_FILE="cmagentpkg"
TMIPKG="TMI_Agent.tar"
LOTUSUSER=""
LOTUSGROUP=""
LOTUS="/opt/lotus"
DEBUG=/dev/null
CMACCOUNT=""
CMURL=""
ENTITYNAME=""
PRODUCT="Control Manager agent for ScanMail 2.6"

silentmode=0

# Defines
ECHO="Echo"
READ="read"
MORE="more"
PING="ping"
iniscript="/tmp/tmpscript"

# TMI installation returns
TMI_NOTHING=23
TMI_INSTALL=231
TMIInstallType=0

# messages inside functions
# in PressAnyKey()
PressEnterMsg="Press Enter to continue ....."

# in AskPath()
PathNameErrorMsg="The path name should be an absolute path name."

# usage()
INSTALLMSG="-install   - install $PRODUCT."
UNINSTALLMSG="-uninstall - uninstall $PRODUCT"
SILENTMSG="-s config-file :  "
HELPMSG="-help      - print this message."

#
# print usage message
#
Usage() {
   Echo "\tUsage $0 [option] [-s configfile]"
   Echo "\toption:"
   Echo "\t\t $INSTALLMSG"
   Echo "\t\t $UNINSTALLMSG"
   Echo "\t\t $HELPMSG"
}

# some common functions
# ex. Echo -n "Echo"
# -n: supress new line character
Echo() {
    if [ "$1" = "-n" ] ; then
        shift 1

        case $arch in
            linux) echo -e -n "$@" ;;
            *)     echo "$@\c" ;;
        esac
    else
        case $arch in
            linux) echo -e "$@" ;;
            *)     echo "$@" ;;
        esac
    fi

    return 0
}

#
# check OS version and domino server
#
CheckState() {
    WORKDIRECTORY=`pwd`

    # figure out the platform
    if [ ! -x /usr/bin/uname ] ; then
        if [ ! -x /bin/uname ] ; then
            ExitInstall "Unknown OS, cannot continue."
        else
            arch=`/bin/uname`
        fi
    else
        arch=`/usr/bin/uname`
    fi

    case $arch in
        SunOS)
	    arch=sol
	    tmp_sopath="$LOTUS/notes/latest/sunspa"
	    datasearchpath="/local/"
	    TMILIBS="TMI_Agent/libTMI_Config.so TMI_Agent/libcrypto.so.0"
	    runlevelrc="/etc/rc2.d"
	    stoprunlevelrc="/etc/rc0.d /etc/rcS.d /etc/rc1.d"
	    INITD=/etc/init.d
	    PING="ping"
	    ;;
        AIX)
	    arch=aix
	    tmp_sopath="$LOTUS/notes/latest/ibmpow"
	    datasearchpath="/local/"
	    TMILIBS="TMI_Agent/libTMI_Config.so TMI_Agent/libcrypto.so"
	    runlevelrc=""
	    stoprunlevelrc=""
	    INITD=/etc/
	    PING="ping -c2"
	    ;;
        Linux)
	    arch=linux
	    tmp_sopath="$LOTUS/notes/latest/linux"
	    datasearchpath="/local/"
	    TMILIBS="TMI_Agent6/libTMI_Config.so TMI_Agent6/libcrypto.so.0"

	    # install to standard "multiuser with network" runlevels
		tmpos=`ls /etc | grep release | grep -i suse`
		if [ $? -eq 0 ] ; then
			runlevelrc="/etc/init.d/rc3.d /etc/init.d/rc5.d"
			stoprunlevelrc="/etc/init.d/rc0.d"
		else
			runlevelrc="/etc/rc.d/rc3.d /etc/rc.d/rc5.d"
			stoprunlevelrc="/etc/rc.d/rc0.d"
		fi
	    INITD=/etc/init.d
	    PING="ping -c2"
	    ;;
        *)
	    ExitInstall "The Operating system: $arch is not supported."
	    ;;
    esac

    id | cut -d' ' -f1 | grep root > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        ExitInstall "You must be super-user (root) to execute this script."
    fi

    case $arch in
        linux) nspsid=`ps -efw|fgrep lotus|fgrep notes|fgrep server` ;;
        *)     nspsid=`ps -ef|fgrep lotus|fgrep notes|fgrep server` ;;
    esac

    if [ "$nspsid" = "" ] ; then
        ExitInstall "Please start the Domino server before running smcminst."
    fi

    return 0
}


#
#
#
PressAnyKey() {
  if [ $silentmode -eq 1 ] ; then # do not PressAnyKey
	return
   fi
   Echo
   Echo $PressEnterMsg
   $READ ans
}

#
#ask parameter
#
AskPath() {
	if [ $silentmode -eq 0 ] ; then
   		while :
   		do
		Echo "\n\t""The Control Manager agent will be installed to the following location:"
		Echo "\t"[$TM_INSTALLDIR] ; $READ ans
		if [ "$ans" != "" ] ; then
	  		firstchar=`echo $ans | cut -c1`
			if [ "$firstchar" != "/" ] ; then
				Echo $ans $PathNameErrorMsg
				continue
			fi
		fi

		case $ans in
			"") if [ ! -z "$TM_INSTALLDIR" ] ; then
				break;
			    fi
			    ;;		
			*)  case $ans in
	  			*)	firstchar=`echo $ans | cut -c1`
					if [ "$firstchar" != "/" ] ; then
						Echo $ans $PathNameErrorMsg
						continue
					fi

					TM_INSTALLDIR=$ans; break;;
			esac;;
		esac
		done
		DisplayMsg "1" "Installpath: $TM_INSTALLDIR"
		SMLN_INSTALLDIR=$TM_INSTALLDIR/SMLN
		TMIPATH=$TM_INSTALLDIR/TMI
	fi
	AGENTPATH=$SMLN_INSTALLDIR/CMAgent

	# create AGENTPATH/temp and parent paths
	test -d $AGENTPATH/temp || mkdir -p $AGENTPATH/temp
}

#
# As name for entity
#
AskEntityName() {

    # get Entity Name
    
    ENTITYNAME=""
    while [ -z "$ENTITYNAME" ]
    do
        Echo "\n\tOnce the agent is connected to the Control Manager server, ScanMail"
        Echo   "\twill show up in a products list on that machine. Type the name you want"
        Echo   "\tScanMail to appear under in that list [$1]."
        Echo -n "\t(Type 'q' to quit): " ; $READ ENTITYNAME
        ChkResp $ENTITYNAME
	if [ -z "$ENTITYNAME" ]; then
            ENTITYNAME=$1
	    return 1
	fi
        if [ "$RESP" = "QUIT" ] ; then
            return 2
        fi
    done
    return 0
}

#
# Display Message on console and/or Agent log file in current dirctory 
#
DisplayMsg(){
  con=$1
  shift
  
  if [ $silentmode -eq 1 ] ; then
  	con="1"
  fi
  
  if [ "$con" -eq "0" ] ; then
      Echo $@

  elif [ "$con" -eq "1" ] ; then
#      Echo $@ >> smcminst.log
      Echo $@
  else
      Echo $@
  fi
}

#
# exit installationn script
#
ExitInstall() {
	DisplayMsg "1" "$@"
	exit 1
}

#
# install SMLN CMAgent package file
#
InstallPkgFile () {

    if [ ! -z "$AGENTPKG_DIR" ] ; then
        mkdir -p $AGENTPKG_DIR
    fi
    echo cmagentdir=$1 > $AGENTPKG_DIR/$AGENTPKG_FILE
}

#
# remove SMLN CMAgent package file
#
RemovePkgFile ()
{
    if [ -f $AGENTPKG_DIR/$AGENTPKG_FILE ]; then
       rm $AGENTPKG_DIR/$AGENTPKG_FILE
    fi
    
    TEMP=`ls $AGENTPKG_DIR`
    if [ -z "$TEMP" ] ; then
       rm -rf $AGENTPKG_DIR
    fi
}


#
# uninstall TMI package
#
Uninstalltmi(){

    Echo
    Echo "Uninstall TMI ..."
	
    TMI_CFG_HINT_FILE=/etc/tmicfgdir
    if [ -f $TMI_CFG_HINT_FILE ]; then
        # HintFile exists
        TMI_PATH=`cat $TMI_CFG_HINT_FILE | grep TMI_CFG_PATH= | cut -d'=' -f2 | cut -d'"' -f2`
        #prevent the content error ( blank or not valid path name)
	if [ -z "$TMI_PATH" ] ; then
        	TMI_PATH=$TMI_DEFAULT_PATH
	fi

        if [ ! -d $TMI_PATH ]; then
            TMI_PATH=$TMI_DEFAULT_PATH
        fi
    else
        TMI_PATH=$TMI_DEFAULT_PATH
    fi

    #uninstall tmi
    Echo "Removing the TMI package ..."
    test -f $TMI_PATH/tmi && $TMI_PATH/tmi stop > $DEBUG
    test -d $TMI_PATH/../TMIBackup && rm -rf $TMI_PATH/../TMIBackup
    test -d $TMI_PATH && rm -rf $TMI_PATH
    test -f /etc/tmicfgdir && rm /etc/tmicfgdir
    Echo "Uninstall TMI finish."
}

#
# check and install TMI package
#
CheckTMIVersion () {

    Echo "\nCheck/Install the TMI package ..."

# get current TMI installation path
    TMI_CFG_HINT_FILE=/etc/tmicfgdir
    if [ -f $TMI_CFG_HINT_FILE ]; then
        # HintFile exists
        TMIPATH=`cat $TMI_CFG_HINT_FILE | grep TMI_CFG_PATH= | cut -d'=' -f2 | cut -d'"' -f2`
	if [ -z "$TMIPATH" ] ; then
        	TMIPATH=$TMI_DEFAULT_PATH
		/bin/rm -f $TMI_CFG_HINT_FILE
	fi
	if [ ! -d $TMIPATH ]; then
            TMIPATH=$TMI_DEFAULT_PATH
	    /bin/rm -f $TMI_CFG_HINT_FILE
        fi

    else
    	if [ -z "$TMIPATH" ] ; then
        	TMIPATH=$TMI_DEFAULT_PATH
	fi
    fi
   
    if [ ! -d $TMIPATH/temp ] ; then
    	mkdir -p $TMIPATH/temp
    fi
    
    StopTMIService
    if [ -f $TMIPATH/TMI.cfg ] ; then
    	TMICFGEXIST=1
    else
        TMICFGEXIST=0
    fi

    test -f ./install_tmi && ./install_tmi INSTALLDIR=$TMIPATH STARTSERVICE=0 ADDRESSTYPE=1 DEBUGLOGPATH=$TMIPATH/temp
    returnvalue=$?
    TMIInstallType=$returnvalue
    if [ $returnvalue -eq $TMI_INSTALL ] ; then
        Message="The TMI package installation was successful. "
        DisplayMsg "1" "$Message" $returnvalue

        if [ $TMICFGEXIST -eq 1 ] ; then
        # tmi update installation because TMI already exists
          TMIInstallType=$TMI_NOTHING
        fi

    elif [ $returnvalue -eq $TMI_NOTHING ] ; then
        # TMI is available and up to date
        Message="The TMI package is up-to-date. "
	DisplayMsg "1" "$Message" $returnvalue
    else
        Message="Unable to install TMI package. "
	DisplayMsg "1" "$Message" $returnvalue
        exit 1
    fi
    return 0
}

#
#
#
smlnpkgadd() {

    PKG=$1
    PKGPATH=$2
    if [ -d /tmp/smlnpkg ] ; then
        /bin/rm -rf /tmp/smlnpkg
    fi

    ( cd /tmp ; mkdir smlnpkg )
    /bin/cat < ./$PKG | ( cd /tmp/smlnpkg ; tar xf - )

    if [ ! -d $PKGPATH ] ; then
        mkdir -p $PKGPATH
    fi
    if [ "$arch" = "aix" ] ; then
    	rm -f $PKGPATH/lib*
    fi 
    cp /tmp/smlnpkg/* $PKGPATH

    if [ $? -ne 0 ] ; then
	DisplayMsg "0" "Unable to copy package files to $PKGPATH."
        rm -rf $PKGPATH
	rm -rf /tmp/smlnpkg
        return 1
    fi
    rm -rf /tmp/smlnpkg
    return 0
}

#
# install tmi start/stop script
#
InstallService () {

	if [ "$arch" != "aix" ] ; then
	if [ ! -f $INITD/smlncmagent ] ; then
		Echo "\nInstall runlevel start/stop script."
		cp $AGENTPATH/smlncmagent $INITD/smlncmagent
	        if [ $? -ne 0 ]; then
	            Echo "Copy $AGENTPATH/smlncmagent to $INITD failed."
	            return 1
	        fi
        fi

	for arg in $runlevelrc
	do
		if [ ! -f $arg/S99smlncmagent ] ; then
			(cd $arg; ln -s $INITD/smlncmagent S99smlncmagent )
			if [ $? -ne 0 ]; then
	            	DisplayMsg "1" "Unable to create the link $AGENTPATH/smlncmagent S99amlnagent."
	            	return 1
			fi
		fi
	done

	for arg in $stoprunlevelrc
	do
		if [ ! -f $arg/K99smlncmagent ] ; then
			(cd $arg; ln -s $INITD/smlncmagent K99smlncmagent )
			if [ $? -ne 0 ]; then
	            	DisplayMsg "1" "Unable to create the link $AGENTPATH/smlncmagent K99amlnagent."
	            	return 1
			fi
		fi
	done
	else
		if [ -f $INITD/rc.smlncmagent ] ; then
			RemoveService
		fi
		if [ ! -f $INITD/rc.smlncmagent ] ; then
		Echo "\nInstall runlevel start/stop script."
		cp $AGENTPATH/smlncmagent $INITD/rc.smlncmagent
	        if [ $? -ne 0 ]; then
	            Echo "Copy $AGENTPATH/smlncmagent to $INITD/rc.smlncmagent failed."
	            return 1
	        fi
                mkitab "smlncmagent:2:once:/etc/rc.smlncmagent start"
		if [ $? -ne 0 ]; then
	            DisplayMsg "1" "Unable to add smlncmagent to inittab file."
	            return 1
	        fi
        	fi	
	fi
}

#
# remove tmi start/stop script
#
RemoveService () {

	Echo "\nRemove runlevel start/stop script."
	if [ "$arch" != "aix" ] ; then
		for arg in $runlevelrc
		do
		if [ -h $arg/S99smlncmagent ] ; then
			rm $arg/S99smlncmagent
			if [ $? -ne 0 ]; then
	            	DisplayMsg "1" "Unable to remove $arg/S99smlncmagent."
	            	return 1
			fi
		fi
		done
		for arg in $stoprunlevelrc
		do
		if [ -h $arg/K99smlncmagent ] ; then
			rm $arg/K99smlncmagent
			if [ $? -ne 0 ]; then
	            	DisplayMsg "1" "Unable to remove $arg/K99smlncmagent."
	            	return 1
			fi
		fi
		done	
	
	
	if [ -f $INITD/smlncmagent ] ; then
	        rm $INITD/smlncmagent
	        if [ $? -ne 0 ]; then
	            Echo "Unable to remove $INITD/smlncmagent."
	            return 1
	        fi
        fi
	else
	  if [ -f $INITD/rc.smlncmagent ] ; then
	        rm $INITD/rc.smlncmagent
	        if [ $? -ne 0 ]; then
	            Echo "Unable to remove $INITD/rc.smlncmagent."
	            return 1
	        fi
	        rmitab smlncmagent
	        if [ $? -ne 0 ]; then
	            DisplayMsg "1" "Unable to remove smlncmagent from inittab file."
	            return 1
	        fi
          fi
	fi
}

#
# check CM agent version
#
CheckAgentVersion () {
        AgentInstallType="install"
}

#
# set up shared libraries search path
#
SetupLibPath () {
    if [ "$arch" = "aix" ] ; then
        if [ -n "$LIBPATH" ] ; then
            LIBPATH=$AGENTPATH:$LIBPATH
        else
            LIBPATH=$AGENTPATH
        fi
        export LIBPATH
    else
        if [ -n "$LD_LIBRARY_PATH" ] ; then
            LD_LIBRARY_PATH=$AGENTPATH:$LD_LIBRARY_PATH
        else
            LD_LIBRARY_PATH=$AGENTPATH
        fi
        export LD_LIBRARY_PATH
    fi
}

#
#
#
InstallAgent() {

    #check package exist
    test ./$AGENTPKG || return

    #install CMAgent
    Echo "Install CMAgent package ..."
    smlnpkgadd $AGENTPKG $AGENTPATH

    if [ $? -ne 0 ] ; then
	    rm -rf $AGENTPATH
	    exit 1
    else
        rm -rf /tmp/pkgagent

        chmod +x $AGENTPATH/EntityMain
        chmod +x $AGENTPATH/getcmacnt
        chmod +x $AGENTPATH/startagent
        chmod +x $AGENTPATH/stopagent
        chmod +x $AGENTPATH/cfgtmi
        chmod +x $AGENTPATH/cfgcma
        chmod +x $AGENTPATH/updcmaver
        chmod +x $AGENTPATH/getprdcnt
        chmod +x $AGENTPATH/smlncmagent

        # add  NotesProgram path 
        AddNotesProgramPath
    
        if [ "$arch" = "aix" ] ; then
            if [ -x $SOPATH/dataseg ] ; then
                Echo "Updating the Control Manager agent for compatibility with Domino 5.09 or higher"
	        $SOPATH/dataseg -s $AGENTPATH/EntityMain > /dev/null 
            fi
        fi
	
	echo SMLN_PATH=\"$SMLN_INSTALLDIR\" > $AGENTPATH/smlnenv
	echo TMI_CFG_HINT_FILE=\"/etc/tmicfgdir\" >> $AGENTPATH/smlnenv
	echo CMAGENT_PATH=\"$SMLN_INSTALLDIR/CMAgent\" >> $AGENTPATH/smlnenv
	
	ReplacePath $AGENTPATH/smlncmagent
		
	CHECKAGENT=$AGENTPATH/agentconfig.sh

	chmod 644 $AGENTPATH/smlnenv

	InstallPkgFile $AGENTPATH
	
        Echo "Control Manager agent installation complete."
        Echo "\nThe agent now needs to be registered with the Control Manager server."

        PressAnyKey
    fi
}

#
# remove Agent from TMI
#

UnconfigAgent() {        
    ENTITYCFG=$INIPATH/Entity.cfg
    if [ ! -r $ENTITYCFG ] ; then
    	# Agent is not configured
    	return 2
    fi
    
    Echo "Unconfigure Control Manager agent ..."
    $AGENTPATH/rmvcma -d $INIPATH
    DelNotesProgramPath

    return 0
}

#
#
#
UninstallAgent() {

    Echo "Uninstall Control Manager agent ..."
    
    SetupLibPath

    UnconfigAgent
    if [ "$?" -ne "0" ] ; then
	return 2
    fi
    # Count how many products still register with local TMI
    $AGENTPATH/getprdcnt
    prdcnt=$?


#    # check if Entities exists
    $AGENTPATH/getcmacnt
    if [ $? -eq 0 ] ; then
      # uninstall TMCM Agent #
      cd $CURRENTDIR
      rm -r $AGENTPATH
      TEMP=`ls $SMLN_INSTALLDIR`
      if [ -z "$TEMP" ] ; then
      	rm -r $SMLN_INSTALLDIR
	TEMP=`ls $TM_INSTALLDIR`
        if [ -z "$TEMP" ] ; then
      	  rm -r $TM_INSTALLDIR
        fi
      fi
      if [ "$?" -ne "0" ] ; then
        Message="$PRODUCT uninstallation failed."
	return 1
      else
	RemoveService
	
	RemovePkgFile
      fi
    fi
    Echo "Uninstallation of $PRODUCT complete."

    if [ $prdcnt -le 0 ] ; then
        Uninstalltmi
	TEMP=`ls $TM_INSTALLDIR`
        if [ -z "$TEMP" ] ; then
      	  rm -r $TM_INSTALLDIR
        fi
    fi
    exit 0
}

#
# check for installed TMI package
#
CheckTMIPkg() {

    TMI_CFG_HINT_FILE=/etc/tmicfgdir
    if [ -f $TMI_CFG_HINT_FILE ]; then
        # HintFile exists
	TMI_PATH=`cat $TMI_CFG_HINT_FILE | grep TMI_CFG_PATH= | cut -d'=' -f2 | cut -d'"' -f2`
	if [ -z "$TMI_PATH" ] ; then
	        Echo "The TMI package folder does not exist."
        	return 1
	fi

        #prevent the content error ( blank or not valid path name)
        if [ ! -d $TMI_PATH ]; then
            Echo "The TMI package folder does not exist."
            return 1
        fi
    else
        Echo "Unable to find the TMI package location."
        return 1
    fi
    return 0
}

#
# check response
#
ChkResp() {

	firstchar=`echo $1 | cut -c1`
	secondchar=`echo $1 | cut -c2`
	if [ "$firstchar" = "" ] ; then
		RESP=$2
	fi
	if [ -z "$secondchar" ] ; then
		case $1 in
		[yY]* )
			RESP=YES ;;
		[nN]* )
			RESP=NO ;;
		[qQ]* )
			RESP=QUIT ;;
        	* )
			RESP=$2 ;;
		esac
	fi
}

#
# Add "NoteProgram=" to notes.ini if not already inside
#
AddNotesProgramPath () {

    # Domino 6 could have no symbolic link to /opt/lotus.
    # Get program directory path from notes.ini
    lotusdir=`grep -i "^NotesProgram=" "$INIPATH/notes.ini" | cut -d= -f2`
    if [ "$lotusdir" = "" ] ; then
        SOPATH=$tmp_sopath
	SetIni a NotesProgram $SOPATH
    else
        SOPATH=$lotusdir
    fi
}

#
# Delete "NoteProgram=" in notes.ini if aded by SM CM agent
#
DelNotesProgramPath () {

    lotusdir=`grep -i "^NotesProgram=" "$INIPATH/notes.ini"`
    if [ "$lotusdir" != "" ] ; then
	SetIni d NotesProgram
    fi
}

#
# Configure Entity 
#
ConfigureEntity() {
    # config Entity information
    Echo "\n\tConfiguring the Control Manager agent for ScanMail 2.6..."
    
    SetupLibPath

    # get Account
    while [ -z "$CMACCOUNT" ]
    do
        Echo "\n\tLog on to the Control Manager server using an administrator-level account such as root:"
        Echo -n "\t(Type 'q' to quit): "

        $READ CMACCOUNT
        ChkResp $CMACCOUNT
        if [ "$RESP" = "QUIT" ] ; then
            return 2
        fi
    done

    ENTITYCFG=$INIPATH/Entity.cfg

    if [ $silentmode -eq 0 ] ; then
    	ENTITYNAME=`hostname`
    	AskEntityName $ENTITYNAME
	ret=$?
	if [ $ret -eq 2 ] ; then
		return 2
    	fi
    fi
    if [ -z "$ENTITYNAME" ]; then
        $AGENTPATH/cfgcma -d $INIPATH -a $CMACCOUNT
    else
        $AGENTPATH/cfgcma -d $INIPATH -a $CMACCOUNT -n $ENTITYNAME
    fi

    if [ $? -ne 0 ] ; then
        DisplayMsg "1" "Unable to Configure/Register Control Manager agent."
        PressAnyKey
        return 1
    fi
    chown $LOTUSUSER $ENTITYCFG
    chgrp $LOTUSGROUP $ENTITYCFG

    return 0
}
   
#
# install CM key file
# function can import CM key file from CM server or use local file 
#     
InstallKeyFile () {
    
    # get server hostname or IP or keyfile
    READY=0
    if [ $silentmode -eq 0 ] ; then
    
    while [ $READY -ne 1 ]
    do
	TEMP=`find $CURRENTDIR -name E2EPublic.dat`
        Echo "\n\tPlease enter"
	Echo "\tthe hostname or IP address of the TMCM server"
	Echo "\tor"
	Echo "\tfilename of server key file [default:$TEMP]."
        Echo -n "\t(Type 'q' to quit): " ; $READ CMURL
        ChkResp $CMURL
        if [ -z "$CMURL" ] && [ -z "$TEMP" ] ; then
            Echo "\nInput is invalid !!"
        elif [ "$RESP" = "QUIT" ] ; then
            return 2
        else
 	    if [ -z "$CMURL" ] && [ -r "$TEMP" ] ; then
	    	CMURL=$TEMP
	    fi
	    
	    Echo "\nChecking $CMURL ..."
	    if [ -f "$CMURL" ] ; then
	    	KEYFILE=1
		READY=1
	    else
	    	KEYFILE=0
		CMHOST=`echo $CMURL | cut -d':' -f1`
            	$PING $CMHOST > /dev/null
            	if [ $? -ne 0 ]; then
                	Echo "\n$CMURL is invalid."
            	else
                	READY=1
            	fi
	    fi
        fi
    done
    
    fi
        
    if [ $KEYFILE -eq 1 ] ; then
    	Echo "\nImport the TMI settings from the key file ..."
        SERVERPUBKEY=$CMURL
        $AGENTPATH/cfgtmi -f $SERVERPUBKEY -a > $DEBUG
    	if [ $? -ne 0 ] ; then
        	DisplayMsg "1" "Unable to import the TMI settings from key file. Returncode:" $?
        	PressAnyKey
        	return 1
    	fi
    else
    	# import TMCM server information
    	Echo "\nImport the TMI settings from the TMCM server ..."
        $AGENTPATH/cfgtmi -s $CMURL -a > $DEBUG

    	if [ $? -ne 0 ] ; then
        	DisplayMsg "1" "Unable to import the TMI settings from TMCM server. Returncode:" $?
        	PressAnyKey
        	return 1
    	fi
    fi
    
    # Check if agent can reach to TMCM host
    TMCM=`grep E2EPublicKey $TMIPATH/TMI.cfg | cut -d';' -f3 | cut -d':' -f1`
    $PING $TMCM > /dev/null
    if [ $? -ne 0 ]; then
        Echo "\nRegistration failed, it may be due to the Control Manager server '$TMCM' which is not listed on DNS or host table."
        Echo "Please check with network administrator and register again."
        PressAnyKey
        return 1
    fi
    
    return 0
}

#
# start TMI service
#
StartTMIService () {
    Echo "Start TMI service ..."
    $AGENTPATH/starttmi > $DEBUG
    if [ $? -ne 0 ] ; then
        DisplayMsg "1" "Unable to to start TMI service. Returncode:" $?
        exit 1
    fi

}

#
# stop TMI service
#
StopTMIService() {

    TMI_CFG_HINT_FILE=/etc/tmicfgdir
    if [ -f $TMI_CFG_HINT_FILE ]; then
        # HintFile exists
	TMI_PATH=`cat $TMI_CFG_HINT_FILE | grep TMI_CFG_PATH= | cut -d'=' -f2 | cut -d'"' -f2`
	
	if [ -z "$TMI_PATH" ] ; then
            Echo "The TMI package folder is not existing."
            return 1
	fi

        #prevent the content error ( blank or not valid path name)
        if [ ! -d $TMI_PATH ]; then
            Echo "The TMI package folder is not existing."
            return 1
        fi
    else
        return 0
    fi
    
    if [ -x $TMI_PATH/tmi ] ; then
        Echo "Stop TMI service ..."
    	$TMI_PATH/tmi stop > $DEBUG
    else
	return 1
    fi
    return 0
}

    
#
# replace _PKG_INSTALL_ROOT_ with work directory
#
ReplacePath() {
  test -z "$1" && return
  sed -e "s,_PKG_INSTALL_ROOT_,$AGENTPATH,g" $1 > $AGENTPATH/temp/pp$$
  cp $AGENTPATH/temp/pp$$ $1
  rm $AGENTPATH/temp/pp*
}

#
# ask only if default directory doesn't exists
#
GetInstallPath() {

	if [ "$arch" != "aix" ] ; then
	  rcscript=$INITD/smlncmagent
	else
	  rcscript=$INITD/rc.smlncmagent
	fi

	if [ -f $rcscript ] ; then
		AGENTPATH=`grep "CMAGENT_PATH=" $rcscript | cut -d= -f2`
		if [ "$AGENTPATH" != "" ] ; then
	  		SMLN_INSTALLDIR=`dirname $AGENTPATH`
			TM_INSTALLDIR=`dirname $SMLN_INSTALLDIR`
			CHECKAGENT=$AGENTPATH/agentconfig.sh
			CheckTMIPkg
                        if [ $? -eq 0 ] ; then
				TMIPATH=$TMI_PATH
			else
				TMIPATH="$TM_INSTALLDIR/TMI"
			fi
		else
   			if [ -d $SMLN_DEFAULT_PATH ] ; then
        			TM_INSTALLDIR=$TM_DEFAULT_PATH
	  			SMLN_INSTALLDIR=$SMLN_DEFAULT_PATH
	  			AGENTPATH=$SMLN_INSTALLDIR/CMAgent
          			TMIPATH=$TMI_DEFAULT_PATH
  			else
          			AskPath
  			fi
		fi
	else
   		if [ -d $SMLN_DEFAULT_PATH ] ; then
        		TM_INSTALLDIR=$TM_DEFAULT_PATH
	  		SMLN_INSTALLDIR=$SMLN_DEFAULT_PATH
	  		AGENTPATH=$SMLN_INSTALLDIR/CMAgent
          		TMIPATH=$TMI_DEFAULT_PATH
  		else
          		AskPath
  		fi
  	fi
	if [ "$arch" = "aix" ] ; then
	                  if [ -n "$LIBPATH" ] ; then
	                    LIBPATH=$TMIPATH:$LD_LIBPATH
	                  else
	                    LIBPATH=$TMIPATH
	                  fi
	                  export LIBPATH
	else
                          if [ -n "$LD_LIBRARY_PATH" ] ; then
	                    LD_LIBRARY_PATH=$TMIPATH:$LD_LIBRARY_PATH
	                  else
	                    LD_LIBRARY_PATH=$TMIPATH
	                  fi
	                  export LD_LIBRARY_PATH
	fi								
	# create AGENTPATH/temp and parent paths
	test -d $AGENTPATH/temp || mkdir -p $AGENTPATH/temp
}

# 
# $1 - a/d/r   $2 - Item   $3 - Value
# $2 is case insensitive, $3 is case sensitive in this funtion
# ex. SetIni a NotesProgram SOPATH
#
SetIni()
{
    if [ -f $iniscript ] ; then
        \rm $iniscript
    fi
    insertmsg="#$2 added by SMLN CM agent installation"
    insertline=`grep -n "$insertmsg" $INIPATH/notes.ini | cut -d: -f1`
    itemline=`grep -n -i "^$2=" $INIPATH/notes.ini |cut -d: -f1`
    if [ "$itemline" != "" ] ;then
        item=`grep -i "^$2=" $INIPATH/notes.ini |cut -d= -f1`
        Echo "ed -s $INIPATH/notes.ini << T_EOF > /dev/null" >>$iniscript
        Echo "/^$item=" >>$iniscript
        case $1 in
        a) # Add specific value
            value=`grep -i "^$2=" $INIPATH/notes.ini |cut -d= -f2`
            if [ "$value" = "" ] ; then
                # No value exists. Add newly.
                Echo "s/$/$3" >>$iniscript
            else
                thisvalue=`Echo "$value" | grep $3`
                if [ "$thisvalue" = "" ] ; then
                    # Add to the end.
                    Echo "s/$/,$3" >>$iniscript
                fi
            fi
            ;;
        d) # Delete whole line only if insertmsg exists
	    if [ ! -z "$insertline" ] ; then
	    	nextline=`expr "$insertline" + 1` 
	    	if [ $nextline -eq $itemline ] ; then 
			Echo ".d" >>$iniscript
        		Echo "/^"$insertmsg"/ " >>$iniscript
			Echo ".d" >>$iniscript
	    	else
			return
		fi
	    fi
            ;;
        r) # Remove specific value
            value=`grep -i "^$2=" $INIPATH/notes.ini |cut -d= -f2`
            if [ "$value" = "$3" ] ; then
                Echo ".d" >>$iniscript # Delete whole line
            else
                value=`grep -i "^$2=" $INIPATH/notes.ini |grep ",$3,"`
                if [ "$value" != "" ]; then
                    Echo "s/,$3,/,/" >>$iniscript
                else
                    value=`grep -i "^$2=" $INIPATH/notes.ini |grep ",*$3,*"`
                    if [ "$value" != "" ]; then
                        Echo "s/,*$3,*//" >>$iniscript
                    fi
                fi
            fi
            ;;
        esac
        Echo "w" >>$iniscript
        Echo "q" >>$iniscript
        Echo "T_EOF" >>$iniscript
    else
        case $1 in
        a) # Add whole line
            grep -i "^$2=" $INIPATH/notes.ini |cut -d= -f1 /dev/null 2>&1
            if [ $? -eq 0 ] ; then
                Echo "ed -s $INIPATH/notes.ini << T_EOF > /dev/null" >>$iniscript
                Echo "?^.*=" >>$iniscript
                Echo ".a" >>$iniscript
		Echo "$insertmsg" >> $iniscript
                Echo "$2=$3" >>$iniscript
                Echo "." >>$iniscript
                Echo "w" >>$iniscript
                Echo "q" >>$iniscript
                Echo "T_EOF" >>$iniscript
            fi
            ;;
        esac
    fi

    if [ -f "$iniscript" ] ; then
        lines=`cat $iniscript | wc -l`
        if [ $lines -gt 5 ] ; then
            sh $iniscript
        fi
    fi

    if [ -f $iniscript ] ; then
        \rm $iniscript
    fi

    return 0
}

#
# check if domino server is started on $INIPATH or $1 partition
#
CheckDominoServer()
{
	lckfile="\~notes.lck"

	if [ $# -ne 0  ] ; then
		TEMP=`find $1 -name $lckfile`
	else
		TEMP=`find $INIPATH -name $lckfile`
	fi

	if [ -z "$TEMP" ] ; then
		return 1
	else
		return 0
	fi
}

#
# check for installed SMLN and running Domino server on this partition
#
Check4SMLN () {
	if [ ! -f $1/smconf.nsf ] ; then
		return 1
        fi

	CheckDominoServer $1
	if [ $? -eq 1 ] ; then
		return 2
	fi
	return 0
}

#
# read common notes settings
# lotususer, lotusgroup, 
#
CommonNotesPart() {
    
    if [ $silentmode -eq 0 ] ; then
        # Support directory name with blank under $LOTUSUSERPATH
        ini_list=`find $datasearchpath -name notes.ini -type f -print 2> /dev/null | awk 'BEGIN {ORS=":"} {print $0}'`
    else
        # $INIPATH is already set as parameter of smcminst
        ini_list=""
    fi

    count1=1
    count2=0
    if [ "$ini_list" != "" ] ; then
        inipath_list=""
        while :
        do
            Ini=`Echo $ini_list | cut -f$count1 -d:`
            if [ "$Ini" = "" ] ; then
                break
            fi

            Help=`dirname "$Ini"`
            cd "$Help"
            DIR=`pwd`

            if [ $setuptype -eq 2 ] ; then
	    	if [ -f $DIR/Entity.cfg ] ; then
                    inipath_list=$inipath_list$DIR!
                    count2=`expr $count2 + 1`
                fi
            else
	    	Check4SMLN $DIR
		if [ $? -eq 0 ] ; then
                	count2=`expr $count2 + 1`
                	inipath_list=$inipath_list$DIR!
		fi
            fi
           count1=`expr $count1 + 1`
        done

        if [ $count2 -ge 1 ] ; then
            Echo "\n\tOption | \tLocation of notes.ini "
            Echo   "\t-------|------------------------------"

            count1=1
            while [ $count1 -le $count2 ]
            do
                DIR=`Echo $inipath_list | cut -f$count1 -d!`
                Echo "\t ["$count1"]   | $DIR/notes.ini\t "
                count1=`expr $count1 + 1`
            done
            Echo "\t ["$count1"]   | others"
	    Echo -n "\n\tSetup now needs to know the location of your notes.ini file."
	    Echo
            Echo -n "\n\tEnter 1 - $count1 to specify the location: " ; $READ BLA
        while :
        do
                expr "$BLA" + 1 > /dev/null 2>&1
                if [ $? -ge 2 ] ; then
                    BLA=0  # this is not number
                fi

                if [ $BLA -gt 0 -a $BLA -le $count1 ] ; then
                    break
                fi
                Echo -n "\n\tPlease select valid option(1-$count1) : " ; $READ BLA
        done
            INIPATH=`Echo $inipath_list | cut -f$BLA -d!`
        fi
    fi

    if [ "$INIPATH" = "" ] ; then
        Echo "\n\tPlease enter the complete Notes data directory path :"
        Echo -n "\tPath > " ; $READ INIPATH
    fi

    if [ ! -s $INIPATH/notes.ini ] ; then
        Echo "\n\tUnable to find the notes.ini file. Exiting ..."
        return 1
    fi

    cd $WORKDIRECTORY

    NOTESDIR=`grep -i "^Directory=" "$INIPATH/notes.ini" | cut -d= -f2`
    if [ "$NOTESDIR" != "$INIPATH" ] ; then
        Echo "\n\tThe Notes data directory is incorrect. Please check"
        Echo "\tthe notes.ini of your Domino server. Exiting ..."
        return 1
    fi
    
    LOTUSUSER=`ls -l "$INIPATH/notes.ini" |awk '{print $3}'`
    LOTUSGROUP=`ls -l "$INIPATH/notes.ini" |awk '{print $4}'`

    NOTESOWNER=`ls -l "$INIPATH/notes.ini" |awk '{print $3}'`
    if [ "$NOTESOWNER" != "$LOTUSUSER" ] ; then
        Echo "\n\tYou have entered an incorrect name of the Unix"
        Echo "\taccount you use to run the Domino server."
        Echo "\n\tPlease check your Domino server configuration. Exiting..."
        return 1
    fi
	Check4SMLN $INIPATH
	ret=$?
	if [ $ret -eq 1 ] ; then
		DisplayMsg "1" "ScanMail for Lotus Notes is not installed on this location."
		return 1
	fi
	if [ $ret -eq 2 ] ; then
		DisplayMsg "1" "Domino server is not running on this location."
		return 1
	fi
    return 0
}

#
# check disk space on install directory
#
CheckDiskSpace () {
  Echo "\n"
  Echo -n "Checking available disk space for the Control Manager agent ..."
  
  case $arch in
        aix)   DSP=`df -k $SMLN_INSTALLDIR | sed -n '2p' | awk '{print $3}'` ;;
        sol)   DSP=`df -k $SMLN_INSTALLDIR | sed -n '2p' | awk '{print $4}'` ;;
        linux) DSP=`df -k $SMLN_INSTALLDIR | sed -n '2p' | awk '{print $4}'` ;;
  esac

  if [ $DSP -ge $1 ] ; then
     Echo OK
  else
     Echo "\n"
     DisplayMsg "0" "Available disk space is not sufficient to install the Control Manager agent."


     exit 0;
  fi
}

#
# $1 - variable name to set value
# $2 - item name in setting file
# ex. SetData sm_unix_user LOTUSUSER
#
SetData() {
    grep "^$2=" $settingfile >> /dev/null
    if [ $? -ne 0 ] ; then
        Echo "\tNo $2 entry in $settingfile. Exiting.."
        exit 1
    fi

    value=`grep "^$2=" $settingfile | cut -d= -f2`

    eval $1=$value

    return 0
}

#
# check for compressed package and uncompress
# 
#
UncompressPkg() {
	if [ -f cmagent.tz ] ; then
		zcat < cmagent.tz | (cd $AGENTPATH/temp; tar xf - )
	else
		cp $AGENTPKG $AGENTPATH/temp
		cp $TMIPKG $AGENTPATH/temp
		cp install_tmi $AGENTPATH/temp
	fi
}

#----------------------------------------------------------------------------
# main start

silentmode=0
setuptype=1
settingfile=""
INSTALL=""
UNINSTALL=""
CHECKAGENT=""
CURRENTDIR=`pwd`
# check platform and running domino server
CheckState

if [ $# -eq 0 ] ; then
	Echo "\n\t1 ..... Install $PRODUCT"
        Echo "\t2 ..... Uninstall $PRODUCT"
        Echo -n "\n\tPlease select the number(1, 2) : " ; $READ setuptype
        expr "$setuptype" + 1 > /dev/null 2>&1
        if [ $? -ge 2 ] ; then
            setuptype=0  # this is not number
        fi
        # $setuptype
        # 1: install 2: uninstall/remove
        if [ $setuptype -ne 1 -a $setuptype -ne 2 ] ; then
            Echo "\n\tInvalid choice. Exiting..."
            exit 1
        fi
	if [ $setuptype -eq 1 ] ; then
        	INSTALL="install"
	else
		UNINSTAGENT="uninstall"	
        fi
fi

# search for command line parameters
while [ $# -gt 0 ]
do
   arg=$1
   case $arg in
   	install|-install)
      		INSTALL="$arg"
		setuptype=1
		shift ;;
	remove|-uninstall)
      		UNINSTAGENT="$arg"
		setuptype=2
      		shift ;;
	-p)
		shift
      		INIPATH="$1"
      		shift
		;;
	-s )
      		silentmode=1
		shift
		if [ -f "$1" ] ; then
			settingfile=$1
		else
			echo "$0: setting file [$2] not found" 1>&2
		fi
		shift
		;;
	-help)    Usage; exit 1 ;;
      
      *)
    	Usage
	exit 1 ;;
	
   esac
done

if [ $silentmode -eq 1 ] ; then
	# set data from a configuration file        
	SetData INIPATH sm_ini_path
	SetData SMLN_INSTALLDIR sm_path
	SetData TMIPATH tmi_path
	SetData CMACCOUNT cm_account
	SetData ENTITYNAME cm_entity_name
	SetData CMURL cm_keyfile
	            Echo "Checking $CMURL ..."
	if [ ! -f "$CMURL" ] ; then
		ExitInstall "Unable to find Keyfile $CMURL ."
	fi

	KEYFILE=1
	AGENTPATH=$SMLN_INSTALLDIR/CMAgent
fi

# get installallation path
GetInstallPath

if [ $setuptype -eq 1 ] ; then
	Echo "\n\tInstallation of $PRODUCT"
fi

if [ $setuptype -eq 2 ] ; then
	Echo "\n\tUninstallation of $PRODUCT"
	TMI_CFG_HINT_FILE=/etc/tmicfgdir
	if [ -f $TMI_CFG_HINT_FILE ]; then
        	# HintFile exists
        	TMI_PATH=`cat $TMI_CFG_HINT_FILE | grep TMI_CFG_PATH= | cut -d'=' -f2 | cut -d'"' -f2`
        	#prevent the content error ( blank or not valid path name)
       		if [ -z "$TMI_PATH" ]; then
            		TMI_PATH=$TMIPATH
        	fi

        	if [ ! -d $TMI_PATH ]; then
            		TMI_PATH=$TMIPATH
        	fi
		TMIPATH=$TMI_PATH
    	fi
fi

# get notes user, group and notes.ini path
CommonNotesPart
if [ $? -eq 1 ] ; then
	exit 1
fi

Echo "\n\t--------------------------------------"
Echo "\t"
Echo "\tLocation of ScanMail files\t : $SMLN_INSTALLDIR"
Echo "\tLoation of TMI component\t : $TMIPATH"
Echo "\tDomino Unix user\t\t : $LOTUSUSER"
Echo "\tDomino Unix group\t\t : $LOTUSGROUP"
Echo "\tLocation of Domino data directory: $INIPATH"

if [ ! -z "$UNINSTAGENT" ] ; then
	Echo "\tMode\t\t\t\t : uninstall"
fi
if [ ! -z "$INSTALL" ] ; then
	Echo "\tMode\t\t\t\t : install"
fi

PressAnyKey

# uncompress packages to temp directory
UncompressPkg
cd $AGENTPATH/temp

# uninstall only TMI and CM agent if parameter is set.
if [ ! -z "$UNINSTAGENT" ] ; then
	UninstallAgent
	exit
fi

# check disk space in MB
CheckDiskSpace 30

# check for TMI
CheckTMIVersion
if [ $? -ne 0 ] ; then
    ExitInstall "Unable to install or update TMI service."
fi

#check Agent Version
AgentInstallType="install"

# set AgentVer.ini variable
AGENTFILE=$AGENTPATH/AgentVer.ini

# check if agent 
CheckAgentVersion
AgentInstallType="install"

if [ "$AgentInstallType" != "nothing" ] ; then
	InstallAgent
	if [ $? -ne 0 ] ; then
    		ExitInstall "Unable to install CM agent."
	fi
        $AGENTPATH/updcmaver  	
fi

# install key from CM server or local key file
# only if TMI is installed
if [ $TMIInstallType -eq $TMI_INSTALL ] ; then
	InstallKeyFile
	ret=$?
	if [ $ret -eq 2 ] ; then
		if [ "$AgentInstallType" = "install" ] ; then
			UninstallAgent
		fi
		Uninstalltmi
		ExitInstall "Quit KeyFile installation."
	fi
	if [ $ret -ne 0 ] ; then
		ExitInstall "Unable to install KeyFile."
	fi
fi

# install scripts to start TMI during boot process 
InstallService
if [ $? -ne 0 ] ; then
	ExitInstall "Unable to install TMI service."
fi

# start TMI service
StartTMIService
if [ $? -ne 0 ] ; then
	ExitInstall "Unable to start TMI service."
fi

# configure Agent
REG_READY=0
while [ $REG_READY -ne 1 ]
do
	# configure or reconfigure agent
	ConfigureEntity
	ret=$?
	if [ $ret -eq 0 ] ; then
		REG_READY=1
	fi
	if [ $ret -eq 1 ] ; then
		ExitInstall "Unable to Configure Control Manager agent."
	fi
	if [ $ret -eq 2 ] ; then
		if [ "$AgentInstallType" = "install" ] ; then
			UninstallAgent
		fi
		ExitInstall "Quit Control Manager agent configuration."
	fi		
done
			
# clean temp. package files
rm $AGENTPATH/temp/$AGENTPKG
rm $AGENTPATH/temp/$TMIPKG
rm $AGENTPATH/temp/install_tmi
cd $CURRENTDIR

exit 0
