#!/bin/sh /etc/rc.common

START=50
DAEMON=crond
realconfig=/etc/crontabs
config=/var/spool/cron/crontabs
LOG_FILE=/var/log/crond.log

crontab_modify(){
	local key=$1
	local cmd=$2
	if [ `grep "${key}" $realconfig/root` -eq 0 ]; then
		echo "$cmd" >> $realconfig/root
	fi
}

service_init(){
    [ ! -d /var/nas ] && mkdir /var/nas
    [ ! -f $realconfig/root ] && touch $realconfig/root
	crontab_modify "everyminuteexec" "*/1 * * * * /etc/init.d/nas/everyminuteexec"
	crontab_modify "everyhourexec" "10 * * * * /etc/init.d/nas/everyhourexec"
	crontab_modify "everydayexec" "20 0 * * * /etc/init.d/nas/everydayexec"
    sed -i '/ntpdate/d' $realconfig/root
    local timemode=`awk -F= '/timemode/ {print $2}' /etc/.default.sys|sed s/[[:space:]]//g`
    if [ "$timemode" = "1" ]; then
        local timeserver=`awk -F= '/timeserver/ {print $2}' /etc/.default.sys|sed s/[[:space:]]//g`
        [ -z "$timeserver" ] && timeserver="pool.ntp.org"
        echo "0 12 * * * ntpdate -b $timeserver" >> $realconfig/root
    fi
    sed -i '/^$/d' $realconfig/root

    rm -fr $config >/dev/null 2>&1
    mkdir -p $config
    cp $realconfig/root $config/root -a    
    while read line
    do
        local path=`echo "$line" | awk '{print $6}'`
        echo "$path" | grep "/etc/init.d/" >/dev/null
        if [ $? -eq 0 ]; then
            local shellname=$(basename $path)
            [ -e "/var/nas/$shellname" ] && rm -f "/var/nas/$shellname"
            cp $path  /var/nas/ -a
        fi
    done < $config/root
    sed -i 's/\/etc\/init.d/\/var/g' $config/root
}

start(){
	service_init

	local pid=`pidof crond`
	if [ -z "$pid" ]; then
		$DAEMON -L $LOG_FILE
	fi
}

stop(){
	killall -9 $DAEMON > /dev/null
}

restart(){
	stop
	sleep 1
	start
}

status_service(){
    local pid=`pidof crond`
    if [ -z "$pid" ]; then
        echo "crond stopped"
    else
        echo "crond running"
    fi
}

