#!/bin/sh
##########################################################     
# HA script to handle the DTB resource operations
#
# OCF instance parameters                                
#       OCF_RESKEY_sync                                  
#		OCF_RESKEY_lang                                  
#            
# Changelog:                                            
# rpm68	- added french language							 
# rpm69 - added backup when DTB is stopped via wrapper 
#		- added synctime = 02:00 when empty 
#		- corrected ldap file to ldapserver file
# rpm70 - handle synctrig.cfg ownership and permissions only if needed
# rpm71 - removing ldapserver and sftpserver, adding DTBconfigFile.xml
# rpm77 - moving from /var/tmp/dtb into /var/pgsql/dtb_config/
# rpm78 - killing processes for TCP server ports: changing netstat to fuser + adding logs
# rpm2.0-4 - OSFOURK-23074 - PRB000062027 System restart caused by high DTB CPU load on CCA
# rpm2.0-8 - OSFOURK-24285 - let more time for stop, check for TIME_WAIT states
##########################################################

# DTB definitions
DTB_WRAPPER=/opt/dtb/bin/dtb-wrapper
DTB_BACKUP=/opt/dtb/bin/dtb-backup
DTB_MANAGER=/opt/dtb/bin/dtb-manager
DTB_INSTALLER=/opt/dtb/bin/dtb-installer
DTB_INIT_INSTALLER=/opt/dtb/bin/init-installer
DTB_CLEANUP_INSTALLER=/opt/dtb/bin/cleanup-installer
DTB_INIT_WINE=/opt/dtb/bin/init-wine
DTB_SYNCTIME=/opt/dtb/bin/synctime
DTB_SYNC_NO="0"
DTB_SYNC_ASSISTANT_PERSDAT="1"
DTB_SYNC_MANAG_PERSDAT="2"
DTB_SYNC_SFTP="3"
DTB_SYNC_ASSISTANT_DISPLAY_NAME="4"
DTB_SYNC_MANAG_DISPLAY_NAME="5"
DTB_SYNC_LDAP="6"
DTB_SYNC_FLAG_FILE=/var/opt/dtb_sync
DTB_EN="0"
DTB_DE="1"
DTB_FR="2"
DTB_LANG_FLAG_FILE=/var/opt/dtb_lang
DTB_REQ_FILES=/opt/dtb/ReqFiles
DTB_MASTER_WINEDIR=/var/pgsql/dtb/DTBMaster/winedir
DTB_CFGDIR=/var/pgsql/dtb_config
DTB_CHECKSUM=/var/pgsql/dtb_config/DTBchecksum
DTB_LIST=/var/pgsql/dtb_config/dir.md5
RPM_VERSION=/var/pgsql/dtb_config/rpmversion
CONFIG_FILE=/var/pgsql/dtb_config/DTBconfigFile.xml

# Initialization:
. ${OCF_ROOT}/resource.d/heartbeat/.ocf-shellfuncs

# Defaults
OCF_RESKEY_sync_default=0
OCF_RESKEY_lang_default=0

: ${OCF_RESKEY_sync=${OCF_RESKEY_sync_default}}
: ${OCF_RESKEY_lang=${OCF_RESKEY_lang_default}}

dtb_installation(){
	# Make the directory where the dir.md5, DTBchecksum and rpmversion files will be stored
	logger -s "*** DTB: *** Checking for $DTB_CFGDIR... ***"
	if [ ! -d "$DTB_CFGDIR" ]; then
		logger -s "*** DTB: *** Creating the $DTB_CFGDIR directory for the first time ***"
		mkdir -p $DTB_CFGDIR
		chmod 777 $DTB_CFGDIR
	else
		logger -s "*** DTB: *** $DTB_CFGDIR exist! ***"
	fi
	
	# Save the actual RPM version in rpmversion file
	rpm -qa | grep dtb >${RPM_VERSION}
	chmod 755 ${RPM_VERSION}
	logger -s "*** DTB: *** The rpm version is: $(head ${RPM_VERSION}) ***"
	
	oldcheck="missing"
	
	# Create the dir.md5 file which contains the md5 checksum list of files from /opt/dtb
	find /opt/dtb/ | xargs md5sum 2>/dev/null 1>${DTB_LIST}
	chmod 755 ${DTB_LIST}
	
	# Compute once again a checksum of dir.md5 and store it in a local variable
	newcheck=$(md5sum ${DTB_LIST} | cut -d ' ' -f 1)
	# the result is like '9ca7e349189847aa8f931092019714ad  dir.md5' so we need to remove the 'dir.md5'
	
	# Check if the DTBchecksum file already exists in $DTB_CFGDIR
	if [ -f ${DTB_CHECKSUM} ]
	then
		# if yes, then store its content in a local variable.
		chmod 755 ${DTB_CHECKSUM}
        oldcheck=`cat ${DTB_CHECKSUM}`
	fi
	
	# Check if the file is still missing or his content has been changed
	if ([ ${oldcheck} == "missing" ] || [ ${oldcheck} != ${newcheck} ])
	then
		logger -s "*** DTB: *** DTB Installation files were updated, DTB needs to be reinstalled ***"
		dtb_stop
		$DTB_INSTALLER DTBMaster status
        if [ $? -eq 0 ]; then
            logger -s "*** DTB: *** DTBMaster is installed; Doing the uninstallation right now ***"
            $DTB_INSTALLER DTBMaster uninstall
        fi	
	    $DTB_INSTALLER DTBServer status
	    if [ $? -eq 0 ]; then
        	logger -s "*** DTB: *** DTBServer is installed; Doing the uninstallation right now ***"
            $DTB_INSTALLER DTBServer uninstall
        fi
		$DTB_CLEANUP_INSTALLER
		# Overvrite or recreate the DTBchecksum file which contains the checksum of dir.md5 file
		md5sum ${DTB_LIST} | cut -d ' ' -f 1 > ${DTB_CHECKSUM}
		chmod 755 ${DTB_CHECKSUM}
	else
		logger -s "*** DTB: *** DTB Installation files are unchanged. ***"
	fi
	
	# Initialize wine environment and installer (the scripts do nothing, if everything is already done)
	$DTB_INIT_INSTALLER
	$DTB_INIT_WINE
	
	oldsync="missing"
	oldlang="missing"
	
	# Check for sync or language flag files and store their contents
	if [ -f ${DTB_SYNC_FLAG_FILE} ]
	then
        	oldsync=`cat ${DTB_SYNC_FLAG_FILE}`
	fi
	
	if [ -f ${DTB_LANG_FLAG_FILE} ]
	then
        	oldlang=`cat ${DTB_LANG_FLAG_FILE}`
	fi

	# Check, if the DTB_Master-synchronization or the DTBServer-language has changed
	if ([ ${oldsync} == "missing" ] || [ ${oldlang} == "missing" ] || [ ${oldsync} != ${OCF_RESKEY_sync} ] || [ ${oldlang} != ${OCF_RESKEY_lang} ])
	then
		logger -s "*** DTB: *** DTBMaster and DTBServer needs to be reinstalled  ***"
		$DTB_INSTALLER DTBMaster status
        if [ $? -eq 0 ]; then
            logger -s "*** DTB: *** DTBMaster is installed; doing uninstallation right now ***"
            $DTB_INSTALLER DTBMaster uninstall
        fi	
	    $DTB_INSTALLER DTBServer status
	    if [ $? -eq 0 ]; then
        	logger -s "*** DTB: *** DTBServer is installed; doing uninstallation right now ***"
            $DTB_INSTALLER DTBServer uninstall
        fi
	fi

	# Install DTB application based on the flags
	$DTB_INSTALLER DTBMaster status
	if [ $? -ne 0 ]; then
		logger -s "*** DTB: *** DTBMaster not installed; doing installation right now ***"
		synctime=$(/opt/webservice/scripts/gethaipsetupentry.sh system.dtb-syncTime)
		if [ -z "$synctime" ]; then #if it is empty
			synctime="02:00"
			/opt/webservice/install/ngs-data-set-ha-ip-properties.sh system.dtb-syncTime=$synctime
		fi
		
		if [ ${OCF_RESKEY_sync} == ${DTB_SYNC_NO} ]; then 
			$DTB_INSTALLER DTBMaster install lang=en sync=no
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_ASSISTANT_PERSDAT} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=hdms
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			$DTB_SYNCTIME $synctime # update synchronisation time from DB
			cp $DTB_REQ_FILES/Assistant/*.req $DTB_MASTER_WINEDIR; [ $? -eq 0 ] && logger -s "*** DTB: *** all .req copied into DTBMaster." || logger -s "*** DTB: *** .req copy failed."
			chown dtbuser:users $DTB_MASTER_WINEDIR/*.req
			if [ -d "/var/pgsql/dtb_backup" ]; then
				echo "99" > /var/pgsql/dtb_backup/DTBMaster/SyncTrig.cfg  # put some strange value in synctrig, so the syncstatus can display the previous sync information.
			fi
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_MANAG_PERSDAT} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=hdms
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			$DTB_SYNCTIME $synctime # update synchronisation time from DB
			cp $DTB_REQ_FILES/Manager/*.req $DTB_MASTER_WINEDIR; [ $? -eq 0 ] && logger -s "*** DTB: *** all .req copied into DTBMaster." || logger -s "*** DTB: *** .req copy failed."
			chown dtbuser:users $DTB_MASTER_WINEDIR/*.req
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_MANAG_DISPLAY_NAME} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=display_name
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			$DTB_SYNCTIME $synctime # update synchronisation time from DB
			cp $DTB_REQ_FILES/Manager/*.req $DTB_MASTER_WINEDIR; [ $? -eq 0 ] && logger -s "*** DTB: *** all .req copied into DTBMaster." || logger -s "*** DTB: *** .req copy failed."
			chown dtbuser:users $DTB_MASTER_WINEDIR/*.req
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_ASSISTANT_DISPLAY_NAME} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=display_name
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			$DTB_SYNCTIME $synctime # update synchronisation time from DB
			cp $DTB_REQ_FILES/Assistant/*.req $DTB_MASTER_WINEDIR; [ $? -eq 0 ] && logger -s "*** DTB: *** all .req copied into DTBMaster." || logger -s "*** DTB: *** .req copy failed."
			chown dtbuser:users $DTB_MASTER_WINEDIR/*.req
			if [ -d "/var/pgsql/dtb_backup" ]; then
				echo "99" > /var/pgsql/dtb_backup/DTBMaster/SyncTrig.cfg  # put some strange value in synctrig, so the syncstatus can display the previous sync information.
			fi
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_SFTP} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=no
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			{ crontab -l -u root; echo '* * * * * /opt/dtb/bin/dtb-sftp'; } | crontab -u root - # create a new crontab job
			# The update of the synctime is done in dtb_start()
		elif [ ${OCF_RESKEY_sync} == ${DTB_SYNC_LDAP} ]; then
			$DTB_INSTALLER DTBMaster install lang=en sync=no
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			{ crontab -l -u root; echo '* * * * * /opt/dtb/bin/dtb-ldap'; } | crontab -u root - # create a new crontab job
			# The update of the synctime is done in dtb_start()
		fi
		echo ${OCF_RESKEY_sync} > ${DTB_SYNC_FLAG_FILE}
		sudo chmod 755 $DTB_SYNC_FLAG_FILE
	fi
	
    $DTB_INSTALLER DTBServer status
    if [ $? -ne 0 ]; then
        logger -s "*** DTB: *** DTBServer not installed; doing installation right now ***"
		if [ ${OCF_RESKEY_lang} == ${DTB_EN} ]; then
			$DTB_INSTALLER DTBServer install lang=en
		elif [ ${OCF_RESKEY_lang} == ${DTB_DE} ]; then
			$DTB_INSTALLER DTBServer install lang=de
		elif [ ${OCF_RESKEY_lang} == ${DTB_FR} ]; then
			$DTB_INSTALLER DTBServer install lang=fr
		fi
		echo ${OCF_RESKEY_lang} > ${DTB_LANG_FLAG_FILE}
		sudo chmod 755 $DTB_LANG_FLAG_FILE
    fi
	
	# Create SyncTrig.cfg if it doesn't exists
	SYNCTRIG_CFG=/var/pgsql/dtb/DTBMaster/winedir/SyncTrig.cfg
	if [ ! -f $SYNCTRIG_CFG ]; then
		echo "" > $SYNCTRIG_CFG
	fi
	
	# Change the ownership, if it's not already changed.
	if [ ! "$(stat -c '%U' $SYNCTRIG_CFG)" == "dtbuser" ]; then 
		sudo chown dtbuser:users $SYNCTRIG_CFG
	fi
	
	# Change the permissions if not already changed
	if [ ! "$(stat -c "%a" $SYNCTRIG_CFG)" == "755" ]; then
		sudo chmod 755 $SYNCTRIG_CFG
	fi
}

dtb_status() {
	logger -s "*** DTB: *** Monitor (${OCF_RESOURCE_INSTANCE}) ***"
	# Let's assume that DTB is running
	retval=$OCF_SUCCESS
	$DTB_WRAPPER DTBMaster status
	status_master=$?
    $DTB_WRAPPER DTBServer status
    status_server=$?
		
	# Print out the result
    if [ $status_master -eq 0 ]; then
	    logger -s "*** DTB: *** DTBMaster is running ***"
    else
        logger -s "*** DTB: *** DTBMaster is not running ***"
    fi
    if [ $status_server -eq 0 ]; then
        logger -s "*** DTB: *** DTBServer is running ***"
    else
        logger -s "*** DTB: *** DTBServer is not running ***"
    fi

	# If the state is not consistent (If one is running and another is not)
	if [ $status_master -ne $status_server ]; then
		logger -s "*** DTB: *** inconsistent state ***"
		# Kill both processes
		for pid in $(ps aux | grep dtb | awk '{print $2}'); do kill $pid; done
		logger -s "*** DTB: *** all DTB processes are killed ***"
		# Check DTB ports state if they are unused.
		logger -s "*** DTB: *** Checking for ports 1500, 1200, 1400, 1700 if they are in use ***"
		used=0; #for logging
		while fuser 1500/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1500 is used by the following PID(s): $(fuser 1500/tcp) ****"
				used=1;
			fi
			fuser -k 1500/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1200/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1200 is used by the following PID(s): $(fuser 1200/tcp) ****"
				used=1;
			fi
			fuser -k 1200/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1400/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1400 is used by the following PID(s): $(fuser 1400/tcp) ****"
				used=1;
			fi
			fuser -k 1400/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1700/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1700 is used by the following PID(s): $(fuser 1700/tcp) ****"
				used=1;
			fi
			fuser -k 1700/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		if [ $used -eq 0 ]; then
			logger -s "*** DTB: *** Ports 1500, 1200, 1400, 1700 are free"
		fi
		return $OCF_ERR_GENERIC
	fi
	
	# If DTB is not running
	if [ $status_master -ne 0 ] && [ $status_server -ne 0 ]; then
		retval=$OCF_NOT_RUNNING
	fi
	return $retval
}

dtb_start() {
	logger -s "*** DTB: *** Start ***"
	# If DTB is not running
	if ! dtb_status 
	then
		# Check if DTB needs to be installed
		dtb_installation
		
		logger -s "*** DTB: *** Restore started ***"
		$DTB_BACKUP r
		logger -s "*** DTB: *** Restore finished ***"
		# Check DTB ports state if they are unused.
		logger -s "*** DTB: *** Checking for ports 1500, 1200, 1400, 1700 if they are in use ***"
		used=0; #for logging
		while fuser 1500/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1500 is used by the following PID(s): $(fuser 1500/tcp) ****"
				used=1;
			fi
			fuser -k 1500/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1200/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1200 is used by the following PID(s): $(fuser 1200/tcp) ****"
				used=1;
			fi
			fuser -k 1200/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1400/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1400 is used by the following PID(s): $(fuser 1400/tcp) ****"
				used=1;
			fi
			fuser -k 1400/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		while fuser 1700/tcp; do
			if [ $used -eq 0 ]; then
				logger -s "*** DTB: *** Port 1700 is used by the following PID(s): $(fuser 1700/tcp) ****"
				used=1;
			fi
			fuser -k 1700/tcp # try to kill it
			sleep 1 # sleep until port is free
		done
		if [ $used -eq 0 ]; then
			logger -s "*** DTB: *** Ports 1500, 1200, 1400, 1700 are free"
		fi
		
		#assume TIME_WAIT
		TimeWait1700=0
		TimeWait1500=0
		TimeWait1400=0
		TimeWait1200=0
		
		while [[ $TimeWait1700 -eq 0 || $TimeWait1500 -eq 0 || $TimeWait1400 -eq 0 || $TimeWait1200 -eq 0 ]]; do
			sleep 5
			# Check if no DTB port is in TIME_WAIT
			netstat -anp | grep '127.0.0.1:1700' | grep 'TIME_WAIT'
			TimeWait1700=$? #zero if TIME_WAIT
			netstat -anp | grep '127.0.0.1:1500' | grep 'TIME_WAIT'
			TimeWait1500=$? #zero if TIME_WAIT
			netstat -anp | grep '127.0.0.1:1400' | grep 'TIME_WAIT'
			TimeWait1400=$? #zero if TIME_WAIT
			netstat -anp | grep '127.0.0.1:1200' | grep 'TIME_WAIT'
			TimeWait1200=$? #zero if TIME_WAIT
		done
			  
		# Then start the DTB application
		$DTB_WRAPPER DTBServer start
		sleep 5
        $DTB_WRAPPER DTBMaster start
		sleep 5
		
		SYNCTRIG_CFG=/var/pgsql/dtb/DTBMaster/winedir/SyncTrig.cfg
		
		# If the DTB is configured for Manager synchronisation then update the login parameters at startup - THIS IS DONE BY THE PORTAL - But not at the right place.
		if ([ ${OCF_RESKEY_sync} == ${DTB_SYNC_MANAG_PERSDAT} ] || [ ${OCF_RESKEY_sync} == ${DTB_SYNC_MANAG_DISPLAY_NAME} ]); then
			$DTB_MANAGER # this writes 11 in synctrig.cfg,
			# OSFOURK-18160 - restore the synctrig.cfg, because after every sync the DTB is restarted, and Manager mode the parameters are reloaded (11 is written in SyncTrig)
			cp /var/pgsql/dtb_backup/DTBMaster/SyncTrig.cfg $SYNCTRIG_CFG; [ $? -eq 0 ] && logger -s "*** DTB: *** SyncTrig.cfg copied into DTBMaster." || logger -s "*** DTB: *** SyncTrig.cfg copy failed."
		fi
		
		# Create SyncTrig.cfg if it doesn't exists
		if [ ! -f $SYNCTRIG_CFG ]; then
			echo "" > $SYNCTRIG_CFG
		fi
		
		# Change the ownership, if it's not already changed.
		if [ ! "$(stat -c '%U' $SYNCTRIG_CFG)" == "dtbuser" ]; then 
			sudo chown dtbuser:users $SYNCTRIG_CFG
		fi
		
		# Change the permissions if not already changed
		if [ ! "$(stat -c "%a" $SYNCTRIG_CFG)" == "755" ]; then
			sudo chmod 755 $SYNCTRIG_CFG
		fi
		
		# if the DTB is configured for SFTP synchronisation, then read the synctime from haipsetup.xml and copy to config file
		if ([ ${OCF_RESKEY_sync} == ${DTB_SYNC_SFTP} ]); then
			if [ -f $CONFIG_FILE ]; then # This file is created by the portal
			    synctime=$(/opt/webservice/scripts/gethaipsetupentry.sh system.dtb-syncTime)
				if [[ $synctime =~ ^[0-2][0-9]:[0-5][0-9]$ ]]; then
					logger -s "*** DTB: *** Copying $synctime from haipsetup.xml into config file, sftp node"
				else
					logger -s "*** DTB: *** The time format in haipsetup.xml is not correct. Defaulting to 02:00 and adding to config file, sftp node"
					synctime="02:00"
				fi
			    # update the SFTP synctime in the config file
				sed -i '/\<sftp-time\>/c\	\<sftp-time\>'$synctime'\<\/sftp-time\>' $CONFIG_FILE
			else
				logger -s "*** DTB: *** Cannot add the synctime from haipsetup.xml. The config file does not exists."
			fi
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
			{ crontab -l -u root; echo '* * * * * /opt/dtb/bin/dtb-sftp'; } | crontab -u root - # create a new crontab job
		fi
		
		# if the DTB is configured for LDAP synchronisation, then read the synctime from haipsetup.xml and copy to dtb config file
		if ([ ${OCF_RESKEY_sync} == ${DTB_SYNC_LDAP} ]); then
			if [ -f $CONFIG_FILE ]; then # This file is created by the portal
			    synctime=$(/opt/webservice/scripts/gethaipsetupentry.sh system.dtb-syncTime)
				if [[ $synctime =~ ^[0-2][0-9]:[0-5][0-9]$ ]]; then
					logger -s "*** DTB: *** Copying $synctime from haipsetup.xml into config file, ldap node"
				else
					logger -s "*** DTB: *** The time format in haipsetup.xml is not correct. Defaulting to 02:00 and adding to config file, ldap node"
					synctime="02:00"
				fi
				# update the LDAP synctime in the config file
				sed -i '/\<ldap-time\>/c\	\<ldap-time\>'$synctime'\<\/ldap-time\>' $CONFIG_FILE
			else
				logger -s "*** DTB: *** Cannot add the synctime from haipsetup.xml. The configuration file does not exists."
			fi
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
			{ crontab -l -u root; echo '* * * * * /opt/dtb/bin/dtb-ldap'; } | crontab -u root - # create a new crontab job
		fi
		
		return $OCF_SUCCESS
	else
		logger -s "*** DTB: *** is already running ***"
		return $OCF_SUCCESS
	fi
}

dtb_stop() {
    logger -s "*** DTB: *** Stop ***"
	# If DTB is running
	if dtb_status
	then
		# Then stop the DTB application
		$DTB_WRAPPER DTBServer stop
		sleep 1
        $DTB_WRAPPER DTBMaster stop
		sleep 5
		
		/opt/dtb/bin/dtb-xserver stop
		# Kill both processes
		for pid in $(ps aux | grep dtb | awk '{print $2}'); do kill $pid; done
		logger -s "*** DTB: *** all DTB processes are killed ***"
		
		# make sure that the DTB ports are closed.
		fuser -k 1200/tcp # DTB Server port
		fuser -k 1500/tcp # DTB Master port
		fuser -k 1400/tcp # Status Server port
		fuser -k 1700/tcp # Clean-Device Server port
		
		logger -s "*** DTB: *** Backup started ***"
		$DTB_BACKUP b
		logger -s "*** DTB: *** Backup finished ***"
		
		# if the DTB is configured for SFTP synchronisation, then read the synctime from config file and copy to haipsetup.xml
		if ([ ${OCF_RESKEY_sync} == ${DTB_SYNC_SFTP} ]); then
			if [ -f $CONFIG_FILE ]; then # This file is created by the portal
				# read the sftp time from config file
				lookingFor="sftp-time";
				stime=$(grep $lookingFor $CONFIG_FILE);
				stime=$(echo $stime | sed "s/<$lookingFor>//g; s/<\/$lookingFor>//g")
				if [[ $stime =~ ^[0-2][0-9]:[0-5][0-9]$ ]]; then
					logger -s "*** DTB: *** Copying $stime from config file into haipsetup.xml"
				else
					logger -s "*** DTB: *** The time format in config file is not correct. Defaulting to 02:00 and adding to haipsetup.xml"
					stime="02:00"
				fi
			else
				logger -s "*** DTB: *** The config file does not exists. Defaulting synctime to 02:00 and adding to haipsetup.xml"
				stime="02:00"
			fi
			/opt/webservice/install/ngs-data-set-ha-ip-properties.sh system.dtb-syncTime=$stime # save synctime into haipsetup
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-sftp'  | crontab -u root - # delete the existing crontab job
		fi
		
		# if the DTB is configured for LDAP synchronisation, then read the synctime from ldap file and copy to haipsetup.xml
		if ([ ${OCF_RESKEY_sync} == ${DTB_SYNC_LDAP} ]); then
			if [ -f $CONFIG_FILE ]; then # This file is created by the portal
				# read the ldap time from config file
				lookingFor="ldap-time";
				stime=$(grep $lookingFor $CONFIG_FILE);
				stime=$(echo $stime | sed "s/<$lookingFor>//g; s/<\/$lookingFor>//g")
				if [[ $stime =~ ^[0-2][0-9]:[0-5][0-9]$ ]]; then
					logger -s "*** DTB: *** Copying $stime from ldap file into haipsetup.xml"
				else
					logger -s "*** DTB: *** The time format in ldap file is not correct. Defaulting to 02:00 and adding to haipsetup.xml"
					stime="02:00"
				fi
			else
				logger -s "*** DTB: *** The ldap file does not exists. Defaulting synctime to 02:00 and adding to haipsetup.xml"
				stime="02:00"
			fi
			/opt/webservice/install/ngs-data-set-ha-ip-properties.sh system.dtb-syncTime=$stime # save synctime into DB
			crontab -u root -l | grep -v '/opt/dtb/bin/dtb-ldap'  | crontab -u root - # delete the existing crontab job
		fi
		
		return $OCF_SUCCESS
	else
		# This is the synchronization case, when DTB is already stopped by the wrapper.
		# Was not running, so the stopping action can be considered successful
		logger -s "*** DTB: *** wasn't running ***"
		
		# but make sure that everything is closed
		/opt/dtb/bin/dtb-xserver stop
		# Kill both processes
		for pid in $(ps aux | grep dtb | awk '{print $2}'); do kill $pid; done
		logger -s "*** DTB: *** all DTB processes are killed ***"
		
		# make sure that the DTB ports are closed.
		fuser -k 1200/tcp # DTB Server port
		fuser -k 1500/tcp # DTB Master port
		fuser -k 1400/tcp # Status Server port
		fuser -k 1700/tcp # Clean-Device Server port
		
		logger -s "*** DTB: *** Backup started ***"
		$DTB_BACKUP b
		logger -s "*** DTB: *** Backup finished ***"
		
		return $OCF_SUCCESS
	fi
	logger -s "*** DTB: *** could not be stopped ***"
	return $OCF_ERR_GENERIC
}

# The following methods only needed to satisfy the OCF-tester
dtb_validate() {
	return $OCF_SUCCESS
}

dtb_promote() {
    return $OCF_SUCCESS
}

dtb_demote() {
    return $OCF_SUCCESS
}

dtb_migrate_to() {
    return $OCF_SUCCESS
}

dtb_migrate_from() {
    return $OCF_SUCCESS
}

dtb_reload() {
    return $OCF_SUCCESS
}

dtb_notify() {
    return $OCF_SUCCESS
}

# Here are the parameters which are passed to Resource Agent
dtb_meta() {
cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="dtb_ra">
<version>1.0</version>
<longdesc lang="en">
This OCF RA starts the DTB application.
</longdesc>
<shortdesc lang="en">dtb</shortdesc>
<actions>
<action name="start"   timeout="60" />
<action name="stop"    timeout="60" />
<action name="monitor" depth="0"  timeout="20" interval="10" />
<action name="meta-data"  timeout="5" />
<action name="validate-all"  timeout="5" />
<parameters>
<parameter name="sync" required="0" unique="0">
<longdesc lang="en">
Controls the DTB Master syncronization. 0=no sync; 1=sync with Assistant - PERSDAT; 2=sync with Manager - PERSDAT; 3=sync with SFTP; 4=sync with Assistant - DISPLAY_NAME; 5=sync with Manager - DISPLAY_NAME; 6=sync with LDAP.
</longdesc>
<shortdesc lang="en">DTB Master Syncronisation</shortdesc>
<content type="integer" default="${OCF_RESKEY_sync_default}"/>
</parameter>
<parameter name="lang" required="0" unique="0">
<longdesc lang="en">
Controls the DTB Server language. 0=english; 1=german.
</longdesc>
<shortdesc lang="en">DTB Server language</shortdesc>
<content type="integer" default="${OCF_RESKEY_lang_default}"/>
</parameter>
</parameters>
</actions>
</resource-agent>
END
exit 0
}

case "$1" in
	meta-data|metadata|meta_data)
		dtb_meta
	;;
	start)
		dtb_start
	;;
	stop)
		dtb_stop
	;;
	monitor)
		dtb_status
	;;
	status)
		dtb_status
	;;
	promote)
		dtb_promote
	;;
	demote)
		dtb_demote
	;;
	validate-all)
		dtb_validate
	;;
	migrate_to)
		dtb_migrate_to
	;;
        migrate_from)
                dtb_migrate_from
        ;;
	reload)
		dtb_reload
	;;
        notify)
                dtb_notify
        ;;
	*)
		logger -s "$0 was called with unsupported arguments: $*"
		exit $OCF_ERR_UNIMPLEMENTED
	;;
esac
