#!/bin/ksh
#
# #ident    @(#)smcs	1.21	02/20/98 SMI
# Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
#
# Sun Messaging Connectivity Services startup Script
#
# NOTE: This script looks best with 4-space tab stops.

# This utility is used to perform various maintenance functions for Smcs.
# By use of command line options, a number of functions may be performed. 
# Note that all of the communications with the Smcs Management Agent are
# performed in the LegacyUtl.java program, and therefore can't be modified
# by a Smcs administrator.

# smcs  [-p <portnumber>] initialize
#  Prompts for a number of variables which are used to configure a freshly
#  installed Smcs configuration.  This can be used with new installations
#  or after using "smcs delete".  You will be prompted for the relevant
#  information.  The Search Base is the DN where ou=People will be placed.
#  The Root DN is DN where Smcs configuration entries will be placed.  The
#  smtp port is the port which is used to transfer messages from the IMTA to
#  the Smcs system.

# smcs [-p <portnumber>] start
#  Starts the Smcs Management Agent, then attempts , the Router, the
#  Transports, and each of the Channels. The -port option is needed only if
#  the MMA is intended to be run on a port other than the default (2585),
#  which is not recommended.  This command is expected to be run from the
#  system initialization scripts, and is by default added to /etc/inittab
#  by the installation script.

# smcs [-p <portnumber>] stop
#  Stops the Smcs components, the MMA, and the license server in a similar
#  process to "smcs start". You probably should only run this when 
#  serious problems occur, the system will be shut down, or a restoration is
#  needed.

# smcs [-p <portnumber>] restart
#  Confirms that the MMA is running, and restarts it if it's not. This is 
#  intended to be run from root's crontab very frequently. It is by default
#  added to run every 10 minutes.

# smcs [-p <portnumber>] nightly
#  Runs a series of maintenance and informational routines, such as cleaning up
#  message queues. This must be run at least once per day,
#  most likely from cron. Configuration for Nightly is located below this 
#  series of comments. The standard output from this command should be mailed 
#  to the Smcs administrator (probably "root").

# smcs [-p <portnumber>] -d <dir> backup
#  Locks the system, and performs a copy of the essential files into another
#  location . This should be run daily, with the output to a
#  dir on the disk. A backup to tape is possible, but backing up to disk,
#  then using normal backup procedures, is generally preferrable. The target
#  directory should be empty, since the procedure will wipe out any existing files
#  in the directory.

# smcs [-p <portnumber> ] -d <dir> restore
#  Performs the complement to the backup operation and should not be 
#  done lightly!  The target  directory should be empty, since 
#  the procedure will wipe out any existing files in the directory.

# smcs delete
#  Removes ALL non-standard files from a Smcs configuration! This is 
#  equivilent to uninstalling and reinstalling Smcs, and should not be 
#  done lightly!  It also removes Smcs installed entires from the
#  running directory.

# smcs [-p <portnumber>] purge
#  Removes all queued messages with status of "Deleted", plus any
#  miscellaneous tracing logs.

# smcs [-p <portnumber>] dirsync
#  Starts a Directory Synchronization based on the current configuration. This
#  command is normally run periodically from cron.

# smcs [-p <portnumber>] setPassword
#  Sets the smcs password to the new value.
#  


################# Configuration options for Smcs Nightly #################

# Change the "1" to "0" to disable the specified function. Any more complex
# changes will need to be done in the "smcs_nightly" routine, below.

set_NightlyOptions()
{
    
	  NIGHTLY_TIDY=1		# Send back undeliverable messages. Strongly recommended.
	  NIGHTLY_R_TMP=1		# Remove temporary files. Strongly recommended.
	  NIGHTLY_PURGE=0		# Purge deleted messages. Useful if "retain deleted" is on.
	  NIGHTLY_BACKUP=0	# Backup configuration to $cfgDir/backupdir
	  
	  ### Not implemented yet
	  #NIGHTLY_QUEUE=1	# View the contents of the queues.
	  #NIGHTLY_STATUS=1	# View the status of each Smcs component.
	  if [[ -f $cfgDir/nightly_opts ]]
	  then
        NIGHTLY_TIDY=`grep NIGHTLY_TIDY $cfgDir/nightly_opts | awk -F= '{printf $2}'`
        NIGHTLY_R_TMP=`grep NIGHTLY_R_TMP $cfgDir/nightly_opts | awk -F= '{printf $2}'`
        NIGHTLY_PURGE=`grep NIGHTLY_PURGE $cfgDir/nightly_opts | awk -F= '{printf $2}'`
        NIGHTLY_BACKUP=`grep NIGHTLY_BACKUP $cfgDir/nightly_opts | awk -F= '{printf $2}'`
	  fi

}


################# Directories #################

set_Directories()
{
	sbinDir=/opt/SUNWmail/gtw/sbin
	logDir=/var/opt/SUNWmail/gtw/logs
	canQueIdxDir=/var/opt/SUNWmail/gtw/tmp/legacy
	canQueMsgDir=/var/opt/SUNWmail/gtw/queues
	lanQueDir=/var/opt/SUNWmail/gtw/lan
	dirSyncDir=/var/opt/SUNWmail/gtw/dirsync
	tmpDir=/tmp
	lockDir=/var/opt/SUNWmail/gtw/locks
	ipcDir=/var/opt/SUNWmail/gtw/ipc
	x500Dir=/var/opt/SUNWmail/gtw/x500
	mcsHomeDir=/var/opt/SUNWmail/gtw/mcshome
	issHomeDir=/var/opt/SUNWmail/gtw/locks/ISS
	licDir=/etc/opt/SUNWmail/gtw/lic
	cfgDir=/etc/opt/SUNWmail/gtw/cfg
	backupDir=/etc/opt/SUNWmail/gtw
	defsDir=/etc/opt/SUNWmail/gtw/defaults
	utildir=/opt/SUNWmail/gtw/lib
# Added for adding gw.adm
	registrydir=/etc/opt/SUNWmail/admin/registry
	adminpropertiesdir=/etc/opt/SUNWmail/admin
}


################# Miscellaneous Definitions #################

set_MiscellaneousDefs()
{
	MMAD_RUNNING=1
	STOPPED_FILE=$lockDir/STOPPED
	MMAD_PORT=`grep GATEWAY.mmadportnumber= $adminpropertiesdir/adminserver.properties|awk -F= '{printf $2}'`
	export MMAD_PORT
	PORT=${MMAD_PORT-"2585"}
	MANAGER=root
	POSTMASTER="postmaster@localhost"
	MAILUSER=inetmail
	OWNERSHIP=$MANAGER:sys
	CRONTMP="/tmp/msvcron.$$"
	PSARGS="-e -o pid -o comm"
	EXIT=0
	CONTINUE=1
	SILENCE=1
	SILENT_START=2
	SILENT_CONNECT_ERROR=3
	SILENT_INITIALIZE_ERROR=4
	RETURN_RESULT=5
	CMD_LINE_ARGS="b:d:D:w:p:r:"


# The Lang should be set to the appropriate locale under /usr/lib/locale
# and TEXTDOMAINDIR should be set if necessary to an alternate path to
# /usr/lib/locale
#	LANG= C
#	TEXTDOMAIN=messages
#	TEXTDOMAINDIR={$BASEDIR}/opt/SUNWmail/admin/lib/locale
	PURGECD=${BASEDIR}/opt/SUNWmail/gtw/lib/purgecd
	PURGE_DELETE_LOG=$logDir/purge_delete_log


	ldapData=.smcs_ldap_data_file
	LDAP_ADD=${SLAPDBASEDIR}/SUNWconn/bin/ldapadd
	LDAP_SEARCH=${SLAPDBASEDIR}/SUNWconn/bin/ldapsearch
	LDAP_DELETE=${SLAPDBASEDIR}/SUNWconn/bin/ldapdelete
	
	if [[ "${DEBUG}" -eq "$TRUE" ]] then
		SMCS_OPTIONS="-Ddebug.components=Gateway -Ddebug.level=1 -Ddebug.file=/tmp/smcs.out"
	else
		SMCS_OPTIONS=
	fi
	SMCS_UTIL=COM.Sun.sunsoft.sims.admin.gw.LegacyUtil
	CONFIG_FILE=COM.Sun.sunsoft.sims.admin.mta.MTAConfigFile

# Added in order to add gw.adm 
	GW_ADMFILE=COM.Sun.sunsoft.sims.admin.gw.ADMFILE
    UTIL=smcsutil
}


################# Find programs #################

set_Programs()
{
	PS=/usr/bin/ps
	if [[ ! -x $PS ]] then
		PS=ps
	fi
	TAR=/usr/bin/tar
	if [[ ! -x $TAR ]] then
		TAR=tar
	fi
	FIND=/usr/bin/find
	if [[ ! -x $FIND ]] then
		FIND=find
	fi
	HEAD=/usr/bin/head
	if [[ ! -x $HEAD ]] then
		HEAD=head
	fi
	XARGS=/usr/bin/xargs
	if [[ ! -x $XARGS ]] then
		HEAD=xargs
	fi
	GREP=/usr/xpg4/bin/grep
	if [[ ! -x $GREP ]] then
		GREP=/usr/bin/grep
		if [[ ! -x $GREP ]] then
			GREP=grep
		fi
	fi
	AWK=/usr/bin/awk
	if [[ ! -x $AWK ]] then
		AWK=awk
	fi
	RM=/bin/rm
	if [[ ! -x $RM ]] then
		RM=rm
	fi
	MV=/bin/mv
	if [[ ! -x $MV ]] then
		MV=mv
	fi
	KILL=/bin/kill
	if [[ ! -x $KILL ]] then
		KILL=kill
	fi
	CMP=/bin/cmp
	if [[ ! -x $CMP ]] then
		CMP=cmp
	fi
	WHO=/bin/whoami
	if [[ ! -x $WHO ]] then
		WHO=/usr/ucb/whoami
		if [[ ! -x $WHO ]] then
			WHO=whoami
		fi
	fi
	LN=/bin/ln
	if [[ ! -x $LN ]] then
		LN=ln
	fi
	CUT=/bin/cut
	if [[ ! -x $CUT ]] then
		CUT=cut
	fi
	CRONTAB=/usr/bin/crontab
	if [[ ! -x $CRONTAB ]] then
		CRONTAB=crontab
	fi
	CHOWN=/usr/bin/chown
	if [[ ! -x $CHOWN ]] then
		CHOWN=chown
	fi
	STTY=/usr/bin/stty
	if [[ ! -x $STTY ]] then
		STTY=stty
	fi
	gettext=/usr/bin/gettext
	if [[ ! -x $gettext ]] then
	    gettext=gettext
	fi
}


########## Parse command line using getopts ##########
parse_Arguments()
{

  while getopts $CMD_LINE_ARGS option
  do
	case $option in
	  
	  d)   iodir=$OPTARG;;
	  
	  p)   PORT=$OPTARG;;
	  
	  ?) echo `$gettext "USAGE: smcs [ -p <port number> ] \n" `
	     echo `$gettext "       [start | stop | restart | nightly | delete | purge | \n" `
		 echo `$gettext "       -d <dir> (backup | restore) | \n" `
		 echo `$gettext "       dirsync | initialize \n" `
		 exit 2;;
	  
	esac
  done
  
  shift $(($OPTIND -1))

  operation=$*
  
  if [[ $operation = "backup" ]] || [[ $operation = "restore" ]]
  then
	if [[ $operation = "backup" ]]
	then
	  if [ -z "$iodir" ]
	  then
		echo `$gettext "Backup needs a -d <dir>  option \n" `
		arg_needed="true"
	  fi
	fi
	if [[ $operation = "restore" ]] 
	then
	  if [ -z "$iodir" ]
	  then
		echo `$gettext "Restore needs a -d <dir>  option " `
		arg_needed="true"
	  fi
	fi
	if [ "$arg_needed" = "true" ]
	then
	  echo `$gettext "USAGE: smcs [-p <port number>]" `
	  echo `$gettext "       [start | stop | restart | nightly | delete | purge | " `
	  echo `$gettext "       -d <dir> (backup | restore) | " `
	  echo `$gettext "       dirsync | initialize " `
	  exit 2
	fi
  fi
  
}


################# Functions #################

smcs_initialize ()
{
	ask_Continue Initialize

	if [[ $CONTINUE = 0 ]]
	then
		EXIT=0
		return
	fi



    searchBaseStr=`$gettext "Please enter the SMCS Search Base DN: " `
	rootStr=`$gettext "Please enter the SMCS Root DN: " `
	hostStr=`$gettext "Please enter the fully qualified local host name: " `
	smtpPortStr=`$gettext "Please enter the IMTA->SMCS SMTP port [27]: " `
	
	read searchBase?"$searchBaseStr"
	read root?"$rootStr"
	read host?"$hostStr"
	read smtpPort?"$smtpPortStr"
	if [[ $smtpPort -eq "" ]]
	then
		smtpPort=27
	fi
	adminStr=`$gettext "Please enter the Administrator DN: " `
	read administrator?"$adminStr"

    pwdStr1=`$gettext "Please enter the directory Administrator password: " `
    pwdStr2=`$gettext "Please confirm the directory Administrator password: " `
	while [[ 1 -eq 1 ]]
	do
		saveterm="$($STTY -g)"       # save terminal state
		$STTY -echo
		read password?"$pwdStr1"
		echo 
		read password2?"$pwdStr2"
		$STTY $saveterm
		if [[ "$password" == "$password2" ]]
		then
			break;
		else
			echo `$gettext "The two passwords do not match \n" `
		fi								
	done
	
	echo
	echo `$gettext "You entered:" `
	echo `$gettext "Search Base Dn =   " `$searchBase 
	echo `$gettext "Root Dn =          " `$root 
	echo `$gettext "Host =             " `$host 
	echo `$gettext "SMTP Port =        " `$smtpPort 
	echo `$gettext "Administrator Dn = " `$administrator 
	

    Y=`$gettext "y" `
	N=`$gettext "n" `
	ansStr=`$gettext "Is this correct?" `
	read answer?"$ansStr ($Y/[$N]) "
	while [[ 1 -eq 1 ]]
	do case $answer in
		$Y*) response=1; break;;
		$N*) response=0; break;;
		*) response=0; break;;
	   esac
	done
	
	if [[ $response = 0 ]] then
		echo `$gettext "NOT performing initialize!" `
		return
	fi
	
	smcs_startMma $SILENT_START
	$utildir/$UTIL init

	echo `$gettext "Initializing..." `
	result=-1
	smcs_tellMmad "initialize $smtpPort $searchBase $root $host $administrator $password"
	
	if [[ $result -eq 0 ]]
	then
	  if [[ ! -f ${BASEDIR}$registrydir/gw.adm ]]
	  then
		mv $registrydir/gw.adm.bak $registrydir/gw.adm
	  fi
	  im.server stop
	  im.server start
	fi
	smcs_removeStoppedLock
}




smcs_setPassword ()
{
	# Check for running mmad
	$JAVA $SMCS_OPTIONS $SMCS_UTIL ping -port $PORT
	result=$?
	if [[ $result -eq 100 ]] then
		echo `$gettext "ERROR: The SMCS Management Agent (mmad) is still not running." `
		echo `$gettext "Run \"smcs start\", then try again." `
		EXIT=1
		MMAD_RUNNING=0
		return
	fi
	
	if [ -z "$password" ]
	then
		saveterm="$($STTY -g)"       # save terminal state
		$STTY -echo
		pwdStr1=`$gettext "Please enter the old password: " `
		pwdStr2=`$gettext "Please enter the new password: " `
		pwdStr3=`$gettext "Please confirm the new password: " `

		read oldPassword?"$pwdStr1"
		while [[ 1 -eq 1 ]]
		do
			read newPassword?"$pwdStr2"
			read newPassword2?"$pwdStr3"
			if [[ $newPassword != $newPassword2 ]]
			then
				echo `$gettext "The new password was not confirmed, please try again." `
			fi
			break
		done
		$STTY $saveterm
	fi

	if [[ $newPassword != $newPassword2 ]]
	then
		echo `$gettext "The new password was not confirmed" `
		EXIT=1
		return
	fi
	
	smcs_tellMmad password "$oldPassword $newPassword"
}


smcs_startMma ()
{
	# start MMA
	MMADPID=`$PS $PSARGS | $GREP mmad | $HEAD -1 | $AWK '{print $1}'`
	if [[ $MMADPID -gt 0 ]]
	then
		if [[ $1 -ne $SILENT_START ]]
		then
			EXIT=2
		str=`$gettext "SMCS Management Agent already running (pid %s)" `
		printf "$str \n" $MMADPID	
		fi
	else
		if [[ -x $sbinDir/mmad ]]
		then
			$sbinDir/mmad -port $PORT
			result=$?
			if [[ $result -ne 0 ]]
			then
				echo `$gettext "SMCS Management Agent FAILED!" ` 
				EXIT=1
			else
				echo `$gettext "SMCS Management Agent..." `
				sleep 3
			fi
		else
			echo `$gettext "SMCS Management Agent MISSING!" `
			EXIT=1
		fi
	fi
}


smcs_stopMma_nonInteractive()
{
	MMAPID=`$PS $PSARGS | $GREP mmad | $HEAD -1 | $AWK '{print $1}'`
}


smcs_start ()
{
	smcs_startMma
	if [[ $EXIT -eq 0 ]]
	then
		smcs_tellMmad start
		smcs_removeStoppedLock
	fi
		
	# since this is usually run from inittab, it would be VERY BAD to return
	# an error level of anything but 0!
	EXIT=0
}


smcs_start_nonInteractive ()
{
	smcs_startMma $SILENT_START
	smcs_removeStoppedLock
}


smcs_stop ()
{
	# touch the stop lock file
	touch $STOPPED_FILE
	if [[ ! -f $STOPPED_FILE ]]
	then
	    tmpStr=`$gettext "ERROR: Could not touch %s !\n" `
		printf "$tmpStr \n" $STOPPED_FILE
		EXIT=1
	fi
	chmod +w $STOPPED_FILE
	
	# check for the MMA's existence. If none, just quit now, otherwise 
	# try to run Legacy.utl and shut stuff down...
	MMAPID=`$PS $PSARGS | $GREP mmad | $HEAD -1 | $AWK '{print $1}'`
	if [[ $MMAPID -gt 0 ]]
	then		
		smcs_tellMmad stop $SILENCE
		
		sleep 3		# sleep, to let MMA go away naturally
		
		# kill MMA if it's still there
		MMAPID=`$PS $PSARGS | $GREP mmad | $HEAD -1 | $AWK '{print $1}'`
		if [[ $MMAPID -gt 0 ]]
		then
			$KILL -INT $MMAPID
			if [[ $? -eq 0 ]]
			then
				echo `$gettext "SMCS Management Agent stopped" `
			else
			    tmpStr=`$gettext "SMCS Management Agent FAILED! (pid %s)!" `
				printf "$tmpStr \n" $MMADPID
				EXIT=1
			fi
		fi
		
	else
		echo `$gettext "SMCS Management Agent stopped" `
	fi
}


smcs_restart ()
{
	if [[ -f $STOPPED_FILE ]]
	then
		# User does not want it restarted
		exit 0
	fi
	
	TMP_FILE=$tmpDir/smcs.$$
	MSG=$tmpDir/smcs_message.$$
	TARGET=mmad
	MAIL=/usr/bin/mail

	$PS $PSARGS | $GREP $TARGET > $TMP_FILE
	$GREP $TARGET $TMP_FILE > /dev/null 2>&1 

	if [[ $? -eq 0 ]]
	then
	    tmpStr=`$gettext "%s is running" `
# i18n Is this a valid statement ?? Check with mark ...
		printf "$tmpStr \n" $TARGET > /dev/null
		EXIT=0
	else
	    tmpStr=`$gettext "%s was not running, starting it up" `
		printf "$tmpStr \n" $TARGET  >> $MSG
		$sbinDir/mmad -port $PORT > /dev/null 2>&1 &
		EXIT=1
	fi

	if [[ -f $MSG ]]
	then
#		$MAIL -s "$TARGET started" $MANAGER < $MSG
# Change is made but need to confirm it with mark ...
	    $MAIL -s "$TARGET started" $POSTMASTER < $MSG
		$RM -f $MSG
	fi

	$RM -f $TMP_FILE
}

smcs_backup ()
{
# Calling Wingra's backup
  $utildir/smcsutil backup $iodir
}

smcs_backup_local ()
{	
	if [ -z "$rootDN" ]
	then
		rootDN="`smcs_tellMmad getRootDN $RETURN_RESULT`"
	fi

	smcs_tellMmad lock $SILENT_CONNECT_ERROR
	smcs_backup_nonInteractive
	smcs_tellMmad unlock $SILENT_CONNECT_ERROR

	if [[ $EXIT -ne 0 ]]
	then
		echo `$gettext "ERROR: tar command returned error status! Removing backup file!" `
	fi
}


smcs_backup_nonInteractive ()
{	
	ldap_backup
	
	filelist="-C $cfgDir $licDir/license.dat $cfgDir/config.dat $dirSyncDir $tmpDir/$ldapData"

	if [ -z "$blocksize" ]
	then
		tarcmd="$TAR -cvhf $iofile $filelist"
	else
		tarcmd="$TAR -cvhbf $blocksize $iofile $filelist"
	fi

	cd $cfgDir
	$tarcmd

	result=$?

	if [[ $result -ne 0 ]]
	then
		let "EXIT = $EXIT + $RESULT"
		$RM $iofile
	fi
}

smcs_restore()
{
#Calling wingra's restore
echo "$utildir/smcsutil restore $iodir"
$utildir/smcsutil restore $iodir

}


smcs_restore_local ()
{
	if [ -z "$rootDN" ]
	then
		rootDN="`smcs_askMmad getRootDN`"
		smcs_stop
	fi

	if [ -z "$password" ]
	then
		saveterm="$($STTY -g)"       # save terminal state
		$STTY -echo
		adminPwdStr=`$gettext "Please enter the directory Administrator password: " `
		read password?"$adminPwdStr"
		$STTY $saveterm
	fi
	
	smcs_restore_nonInteractive
	if [[ $EXIT -eq 99 ]]
	then
	    tmpStr=`$gettext "Cannot find %s\n" `
		printf "$tmpStr \n" $iofile	
	fi
}


smcs_restore_nonInteractive ()
{
	smcs_delete $SILENCE

	originalDirectory=`pwd`
	cd $cfgDir

	if [[ ! -f $iofile ]]
	then
		iofile="$originalDirectory/$iofile"
		if [[ ! -f $iofile ]] then
			EXIT=99
			return
		fi
	fi

	if [ -z "$blocksize" ]
	then
		tarcmd="$TAR -xvpf $iofile"
	else
		tarcmd="$TAR -xvpbf $blocksize $iofile"
	fi

	$tarcmd
	EXIT=$?
	if [[ $EXIT -ne 0 ]]
	then
		return
	fi

	if [ -z "$rootDN" ]
	then
		$sbinDir/mmad -port $PORT > /dev/null 2>&1 &
		sleep 3
		rootDN="`smcs_tellMmad getRootDN $RETURN_RESULT`"
		sleep 3
		smcs_stopMma_nonInteractive
	fi

	ldap_delete
	EXIT=$?
	if [[ $EXIT -ne 0 ]]
	then
		return
	fi

	ldap_restore
	EXIT=$?
	if [[ $EXIT -ne 0 ]]
	then
		return
	fi

	smcs_start
}


## deletes all smcs files which are created after installing Smcs. The 
## status after executing this function is as that after installing Smcs 
## software.
smcs_delete ()
{
# Calling Wingra's delete
  $utildir/smcsutil delete
}


smcs_delete_local ()
{

  smcs_tellMmad delete
  $utildir/smcsutil delete
  result=$?
  if [[ $result == 0 ]]
  then
	$JAVA $SMCS_OPTIONS $CONFIG_FILE -O remove_legacy
	grep -v "sims_gateway " /etc/opt/SUNWmail/imta/imta.cnf > /tmp/imta.tmp
	mv /tmp/imta.tmp /etc/opt/SUNWmail/imta/imta.cnf
	
	if [ -f ${BASEDIR}/etc/opt/SUNWmail/admin/registry/gw.adm ]
	then
	  mv ${BASEDIR}/$registrydir/gw.adm ${BASEDIR}/$registrydir/gw.adm.bak
	fi
	im.server stop
	im.server start
  fi

}


smcs_deleteConfig_nonInteractive ()
{
	(   # redirect all errors to the null device, start here...

	$PURGECD -l $PURGE_DELETE_LOG

	#	smcs_delete_backup
	$RM -rf $lanQueDir/* 
	$RM -rf $lockDir/*
	$RM -rf $canQueIdxDir/*
	$RM -rf $canQueMsgDir/*
	$RM -rf $ipcDir/*
	$RM -ff $cfgDir/config.dat
	$RM -rf $dirSyncDir/*
	
	return)2>/dev/null    # redirect all errors to the null device, end here
}


smcs_delete_backup ()
{
	$RM -rf $cfgDir/backup.tar
	return
}


smcs_purge ()
{
    result=-1
	smcs_tellMmad purge
	if [[ $result -eq 0 ]]
	then
	  echo "Purging .DEL files from /var/opt/SUNWmail/gtw/lan/ subdirectories"
	  /usr/bin/find /var/opt/SUNWmail/gtw/lan -name "*.DEL" -print | xargs -iX /bin/rm -f X
	fi
	
}


smcs_dirsync ()
{
	if [[ ! -f $STOPPED_FILE ]]
	then
		smcs_tellMmad dirsync
	fi
}


smcs_nightly ()
{
	if [[ -f $STOPPED_FILE ]]
	then
		# User does not want it restarted
		exit 0
	fi

	echo SMCS Nightly starting at `date`
	
	# Tell Smcs Utility to nightly
	echo
	if [[ $NIGHTLY_TIDY -gt 0 ]]
	then
		NIGHTLY_OPTS="$NIGHTLY_OPTS -tidy"
	fi
		
#		if [[ $NIGHTLY_QUEUE -gt 0 ]] then
#			NIGHTLY_OPTS="$NIGHTLY_OPTS -queue"
#		fi
#		if [[ $NIGHTLY_STATUS -gt 0 ]] then
#			NIGHTLY_OPTS="$NIGHTLY_OPTS -status"
#		fi
		
 	smcs_tellMmad "nightly $NIGHTLY_OPTS"

	if [[ $NIGHTLY_R_TMP -gt 0 ]] then
		DAYS=3
		echo
	    tmpStr=`$gettext "Removing trace and retained temporary files older than %s day(s)..." `
		printf "$tmpStr \n" $DAYS
		$FIND $tmpDir/.legacy/* -mtime +$DAYS -print -exec $RM -f {} \;
	fi
	
	
	if [[ $NIGHTLY_PURGE -gt 0 ]]
	then
		echo
		echo `$gettext "Purging retained deleted messages..." `
		smcs_purge
	fi


	if [[ $NIGHTLY_BACKUP -gt 0 ]] then
		echo
		if [[ ! -d $backupDir/backup ]]
		then
		  mkdir $backupDir/backup
		fi
		iodir=$backupDir/backup
		tmpStr=`$gettext "Doing SMCS Backup to %s..." `
		printf "$tmpStr \n" $iodir
		smcs_backup
	fi

	echo
	echo Smcs Nightly done at `date`
}


smcs_removeStoppedLock ()
{
	# remove stop lock file
	if [[ -f $STOPPED_FILE ]]
	then
		$RM -f $STOPPED_FILE
		result=$?
		if [[ $result -ne 0 ]] then
		     tmpStr=`$gettext "ERROR: Cannot remove %s !" `
			printf "$tmpStr \n" $STOPPED_FILE
			EXIT=1
		fi
	fi
}


ldap_backup ()
{
	allObjects=`$LDAP_SEARCH -b $rootDN "objectclass=*" dn`
		
	for object in $allObjects
	do
		if [[ $object = [oO][uU]=[cC][hH][aA][nN][nN][eE][lL][sS]* ]]
		then
			$LDAP_SEARCH -L -b "$object" "objectclass=*" > $tmpDir/$ldapData
			break
		fi
	done
}


ldap_delete ()
{
	allObjects=`$LDAP_SEARCH -b $rootDN "objectclass=*" dn`
		
	for object in $allObjects
	do
		if [[ $object = [oO][uU]=[cC][hH][aA][nN][nN][eE][lL][sS]* ]]
		then
			channels=`$LDAP_SEARCH -b "$object" -s sub "objectclass=*" dn`
			skipParent=1
			for channel in $channels
			do
				if [[ $skipParent -eq 1 ]]
				then
					skipParent=0
				else
					$LDAP_DELETE -D "$dirAdminDN" -w $password "$channel"
				fi
			done
			$LDAP_DELETE -D "$dirAdminDN" -w $password "$object"
			break
		fi
	done	
}


ldap_restore ()
{
	$LDAP_ADD -D "$dirAdminDN" -w $password -f $tmpDir/$ldapData
}


require_root ()
{
	if [[ `$WHO` != "root" ]]
	then
	    tmpStr=`$gettext " You must be root to run %s " `
		printf "$tmpStr \n" $operation
		exit 1
	fi
}


smcs_test ()
{
	smcs_tellMmad test
}


# Runs the LegacyUtil java program.  This routine takes
# up to two parameters.  The first is the argument to LegacyUtil.
# the second is an optional flag which will cause this routine to
# fail silently if the mmad cannot be contacted (SILENT_CONNECT_ERROR)
# by LegacyUtil, or the password is not yet set (SILENT_INITIALIZE_ERROR),
# or return the result (RETURN_RESULT) if it is not a connect or initialize error.

smcs_tellMmad ()
{	
	# Tell Legacy Utility to do something
	$JAVA $SMCS_OPTIONS $SMCS_UTIL -port $PORT $1
	result=$?
	if [[ $result -eq 100 ]]
	then
		if [[ $2 -ne $SILENT_CONNECT_ERROR ]]
		then
			echo `$gettext "ERROR: The SMCS Management Agent (mmad) does not appear to be running," `
			echo `$gettext "please use \"smcs start\" before trying this operation again." `
			EXIT=1
			MMAD_RUNNING=0
		fi
	elif [[ $result -eq 101 ]]
	then
		if [[ $2 -ne $SILENT_INITIALIZE_ERROR && $2 -ne $SILENCE ]]
		then
			echo `$gettext "WARNING: No site password has been set. Please use \"smcs initialize\"" `
			echo `$gettext "         to configure smcs before proceeding." `
			EXIT=1
		fi
	elif [[ $result -ne 0 ]]
	then
		if [[ $2 -ne $RETURN_RESULT ]]
		then
		  tmpStr=`$gettext "ERROR: The SMCS Management Utility exited with an error.(%s) "`
		  printf "$tmpStr \n" $RESULT
#			echo `$gettext "ERROR: The SMCS Management Utility exited with an error (" $RESULT ")." `
			EXIT=1
		else
			return $result
		fi
	fi
	return
}


ask_Continue ()
{
	CONTINUE=1
    tmpStr=`$gettext "WARNING: %s is a non-reversible, destructive operation! " `
	printf "$tmpStr \n" $1
	
	Y=`$gettext "y" `
	N=`$gettext "n" `
	sureStr=`$gettext "Are you sure you want to continue? " `
	read answer?"$sureStr ($Y/[$N]) "
	while [[ 1 -eq 1 ]]
	do case $answer in
		$Y*) response=1; break;;
		$N*) response=0; break;;
		*) response=0; break;;
	   esac
	done
	
	if [[ $response = 0 ]]
	then
	    tmpStr=`$gettext "NOT performing %s !" `
		printf "$tmpStr \n" $1
		CONTINUE=0
	fi
}


################# Main #################

if [[ -f `/bin/pkginfo -r SUNWimadm`/opt/SUNWmail/admin/lib/libutil.sh ]]
then
    . `/bin/pkginfo -r SUNWimadm`/opt/SUNWmail/admin/lib/libutil.sh
	runtime_environment		# found in libutil.sh
else
    echo `$gettext "Unable to find shared library" `
    exit 1
fi

set_Directories
set_NightlyOptions
set_MiscellaneousDefs
set_Programs
parse_Arguments $*
require_root

if [[ $operation = "start" ]]
then
	smcs_start
elif [[ $operation = "stop" ]]
then
	smcs_stop
elif [[ $operation = "backup" ]]
then
	smcs_backup
elif [[ $operation = "restore" ]]
then
	ask_Continue Restore
		
	if [[ $CONTINUE = 1 ]]
	then
		smcs_restore
	fi
elif [[ $operation = "restore_nonInteractive" ]]
then
	smcs_restore
elif [[ $operation = "delete" ]]
then
	ask_Continue Delete
		
	if [[ $CONTINUE = 1 ]]
	then 
		smcs_delete_local
	fi	
elif [[ $operation = "delete_nonInteractive" ]]
then
		smcs_delete	
elif [[ $operation = "purge" ]]
then
	smcs_purge
elif [[ $operation = "initialize" ]]
then
	smcs_initialize
elif [[ $operation = "setPassword" ]]
then
	smcs_setPassword

	
	# Usually only called from cron
	
elif [[ $operation = "restart" ]]
then
	smcs_restart
elif [[ $operation = "nightly" ]]
then
	smcs_nightly
elif [[ $operation = "dirsync" ]]
then
	smcs_dirsync
elif [[ $operation = "test" ]]
then
	smcs_test
elif [[ $operation = "ldap_delete" ]]
then
	ldap_delete
	
	## Called from gui only
	
elif [[ $operation = "start_nonInteractive" ]]
then
	smcs_start_nonInteractive
elif [[ $operation = "backup_nonInteractive" ]]
then
	smcs_backup_nonInteractive
elif [[ $operation = "deleteConfig_nonInteractive" ]]
then
	smcs_deleteConfig_nonInteractive
else	
    tmpStr=`gettext "Unknown command: %s \n" `
	printf "$tmpStr \n" $operation
	EXIT=1
fi

exit $EXIT










