#!/bin/sh

PKG_NAME="BackupPlanner"
KOPATH=/usr/local/zy-pkgs/lib
BINPATH=/usr/local/zy-pkgs/bin
ZYBACKUP_LOGS="/usr/local/zy-pkgs/config/${PKG_NAME}/ZYBACKUP_LOGS"

kill_process()
{ 
	TERMINATED="0"
	
	if [ "${1}" == "" ]; then
		echo "BYE"
		return
	fi

	echo "killing ${1}"	
	killall ${1}
	
	for i in 1 2
	do
		echo "${i} second"
		sleep ${i}

		RESULT="`ps| grep ${1} | grep -v grep`"
		if [ "${RESULT}" == "" ]; then
			echo "You are terminated!"
			TERMINATED="1"
			break;
		fi
	done

	if [ "${TERMINATED}" == "0" ]; then
		echo "still survive? KILL U AGAIN!!!"
		killall -9 ${1}
	fi
	
	return
}

if [ "$1" == "status" ]; then
	echo "Built-in"

elif [ "$1" == "startup" ]; then

	###### handle log file size
	if [ -f ${ZYBACKUP_LOGS} ]; then
		cat ${ZYBACKUP_LOGS} | ( while read log_file ; do
			echo "### ${log_file} ###"
			if [ -f ${log_file} ]; then
				echo "-> ${log_file} exists"
				size=`du ${log_file} | awk -F' ' '{print $1}'`
				if [ ${size} -gt 256 ]; then
					echo "-> remove ${log_file}"
					tail -n 100 ${log_file} > ${log_file}.bak
					rm ${log_file}
				fi	
			fi
		done ) || exit 1
	fi

	###### check if cifs.ko is already included in system modules
	lsmod | grep "^cifs "
	if [ "$?" != "0" ]; then
		echo "Inserting cifs.ko module ..."
		insmod $KOPATH/cifs.ko
	fi

	# NOTE: 
	#	The recovery script spends a lot of time when there are too many available modules in target zysync server,
	#	and this will cause a longer boot period. So we removed it.
#	###### recover the remote target paths of all backup jobs with sync type
#	if [ -x $BINPATH/recover_zysync_job.sh ]; then
#		echo "Recovering remote target of sync backup job ..."
#		$BINPATH/recover_zysync_job.sh >> /i-data/.system/BackupPlanner.log
#	fi

	###### start zysync server
	if [ -x $BINPATH/start_zysync_server.sh ]; then
	        echo "Starting zysync server ..."
		/bin/nice -n 17 $BINPATH/start_zysync_server.sh
	fi

	###### start stunnel server
	if [ -x $BINPATH/start_stunnel_server.sh ]; then
		echo "Starting stunnel server ..."
		/bin/nice -n 17 $BINPATH/start_stunnel_server.sh
	fi

elif [ "$1" == "shutdown" ]; then
	# schedule_controller is a daemon included in firmware, not package.
	# We don't need to kill it here. andy - 20090608
	#killall schedule_controller
	kill_process zysync
	kill_process stunnel
	#rmmod cifs

elif [ "$1" == "getlink" ]; then
	echo "${PKG_NAME}/backup_main.html:${PKG_NAME}/backupRestoreByTarget.html"

fi

exit 0
