#!/bin/sh 
# COPYRIGHT (C) NEC CORPORATION 2009, 2010
# Rev.8

# Source function library.
. /opt/nec/hasdrtc/drtc_functions
#. ./drtc_functions;			#debug
[ -f /etc/hasdrtc.conf ] && . /etc/hasdrtc.conf

NR_WRETRY=${NR_WRETRY=50}
SLEEP_WRETRY=${SLEEP_WRETRY=10}
DELAY_SHUTDOWN=${DELAY_SHUTDOWN=120}
DELAY_REBOOT=${DELAY_REBOOT=900}

MESSAGE1=waitdrtc
LEVEL_SHUTDOWN=0
LEVEL_REBOOT=6

set_delay() {
	local RUNLEVEL=`/sbin/runlevel | cut -d " " -f 2`
	if ((RUNLEVEL == LEVEL_SHUTDOWN)); then DELAY=$DELAY_SHUTDOWN;
	elif ((RUNLEVEL == LEVEL_REBOOT)); then DELAY=$DELAY_REBOOT;
	else DELAY=0;
	fi
	print_log DBG "RUNLEVEL($RUNLEVEL) DELAY($DELAY)"
}

wait_sub () {
	print_log DBG "check Just-Time"
	diff_seconds
	if ((DIFFSECONDS < DELAY)); then
		print_log INF "wait start(${DIFFSECONDS}sec)"
		local DM=$(( $DIFFSECONDS / 60 + 1 ))
		/usr/bin/wall "Please wait for ${DM}m. And will begin shutdown."
		sleep_cnt "Please wait for " $DIFFSECONDS
		drtc_exe "-WAIT" $NR_WRETRY $SLEEP_WRETRY
	fi
}

check_wait () {
	if (($DELAY == 0)); then return; fi
	get_systime
	print_log DBG "--- waitdrtc start ---"
	if [ $(($CYEAR  % 2)) -eq 0 -a $(($CYEAR / 10 % 2)) -eq 1 ]	\
	  && [ "$CMONTH" = "02" -a \( "$CDATE" = "28" -o "$CDATE" = "29" \) ]; then
		wait_sub
	fi
}

get_param NR_WRETRY -PLUS
get_param SLEEP_WRETRY -PLUS
get_param DELAY_SHUTDOWN -ZERO_PLUS
get_param DELAY_REBOOT -ZERO_PLUS
set_delay
check_wait

