#!/bin/sh
#
# $Id$
#-------------------------------------------------------------------------------
# TeamFile scheduler script
#
# Copyright (c) 2006,2007 COMPUTER HI-TECH INC., All rights reserved.
#-------------------------------------------------------------------------------

LANG=C
export LANG
#-------------------------------------------------------------------------------
# env setting
#-------------------------------------------------------------------------------
if test -d "${TF_HOME}"; then
	MT_FUNCTION_HOME="${TF_HOME}/www/bin"
	MT_FUNCTION="${MT_FUNCTION_HOME}/mt-lib"
else
	if test -f "./mt-lib"; then
		MT_FUNCTION_HOME="."
	else
		MT_FUNCTION_HOME="/usr/local/teamfile/www/bin"
	fi
	MT_FUNCTION="${MT_FUNCTION_HOME}/mt-lib"
fi

if test ! -f ${MT_FUNCTION}; then
	echo "The configuration script \"${MT_FUNCTION}\" was missing. Please check it."
	exit 1
fi

# read functions and configuration
. ${MT_FUNCTION}

#-------------------------------------------------------------------------------
# Define fixed values
#-------------------------------------------------------------------------------
CRON_DIR="/usr/local/teamfile/www/bin/cron"
LOCK_FILE="/var/run/tfscheduler.pid"
LOG_FILE="/var/log/teamfile/tfscheduler.log"

# (note) Unit: byte
MAX_LOG_SIZE="1048576"

#-------------------------------------------------------------------------------
# Log functions
#-------------------------------------------------------------------------------
initLog() {
	# check size
	F_SIZE=`find ${LOG_FILE} -printf '%s'`
	if test -n "${F_SIZE}" && test `expr $F_SIZE` -gt `expr $MAX_LOG_SIZE`; then
		rm -f ${LOG_FILE}
		touch ${LOG_FILE}
	fi
}

writeLog() {
	msg="$1"

	echo "# `date` : $msg" >> ${LOG_FILE}
}

#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------

# initialize logfile
initLog

# LOCK this script
lockscript ${LOCK_FILE}

#
# get jobs sciprt list
#
SCRIPT_LIST=`find ${CRON_DIR} -type f -maxdepth 1 -print`

#
# execute ALL script
#
for f in ${SCRIPT_LIST};
do
	if test -x $f; then
		writeLog "Running $f"
		$f
	fi
done

# UNLOCK this script
unlockscript ${LOCK_FILE}

exit 0

