#!/bin/sh
# Program:
# The value of TZ is of the form: 	std offset dst offset, rule
# where ruel has the form: 		date[/time],date[/time] 
# The format of date: Jn
# (There are 3 format, see http://leaf.sourceforge.net/doc/buci-tz3.html "Specification of the TZ variable")
# Jn: The Julian day n (1 <= n <= 365). Leap days shall not be counted. That is, in all years-including leap 
#     years-February 28 is day 59 and March 1 is day 60. It is impossible to refer explicitly to the 
#     occasional February 29.
# History:
# 2010/12/15	kenneth		First release

usage () {
        echo "$0 [start|stop]"
        exit 1
}
main_start()
{

DAYLIGHT_MODE=`rdcsman 0x00070021 u32`

#Set DST time by UI
DS_MM=`rdcsman 0x00070022 u32`
DS_DD=`rdcsman 0x00070024 u32`
DS_HH=`rdcsman 0x00070026 u32`
DE_MM=`rdcsman 0x00070023 u32`
DE_DD=`rdcsman 0x00070025 u32`
DE_HH=`rdcsman 0x00070027 u32`

DS_WEEK=`rdcsman 0x00070028 u32`
DS_DAYWEEK=`rdcsman 0x00070030 u32`
DE_WEEK=`rdcsman 0x00070029 u32`
DE_DAYWEEK=`rdcsman 0x00070031 u32`

if [ $DAYLIGHT_MODE -eq 1 ]; then
    if [ $DE_MM -lt 10 ] ; then
    	E_MM="0$DE_MM"
	else
        E_MM="$DE_MM"
    fi
    if [ $DE_DD -lt 10 ] ; then
        E_DD="0$DE_DD"
	else
		E_DD="$DE_DD"
    fi
    if [ $DE_HH -lt 10 ] ; then
        E_HH="0$DE_HH"
    else
        E_HH="$DE_HH"
    fi
    if [ $DS_MM -lt 10 ] ; then
        S_MM="0$DS_MM"
    else
        S_MM="$DS_MM"
    fi
    if [ $DS_DD -lt 10 ] ; then
        S_DD="0$DS_DD"
    else
        S_DD="$DS_DD"
    fi
    if [ $DS_HH -lt 10 ] ; then
        S_HH="0$DS_HH"
    else
        S_HH="$DS_HH"
    fi
	shif="00"
	S_YY=`date +%Y`
	#echo "S_MM=$S_MM,S_DD=$S_DD,S_HH=$S_HH,shif=$shif,S_YY=$S_YY"
    	#echo "E_MM=$E_MM,E_DD=$E_DD,E_HH=$E_HH,shif=$shif,S_YY=$S_YY"
	DST_STAR=`date -d "$S_MM$S_DD$S_HH$shif$S_YY" +%j` #the nth day of the year:1~366
    	DST_END=`date -d "$E_MM$E_DD$E_HH$shif$S_YY" +%j`  #the nth day of the year:1~366
	#echo "DST_STAR=$DST_STAR.DST_END=$DST_END"

	STD=`rdcsman 0x00070001 str` 
	DST=`date +%Z` #get TimeZone string
	echo "$STD$DST,J$DST_STAR/$S_HH,J$DST_END/$E_HH" > /etc/TZ 

elif [ $DAYLIGHT_MODE -eq 2 ]; then
#EST+5EDT,M4.1.0/2,M10.5.0/2
	STD=`rdcsman 0x00070001 str`
	DST=`date +%Z` #get TimeZone string
	echo "$STD$DST,M$DS_MM.$DS_WEEK.$DS_DAYWEEK/$DS_HH,M$DE_MM.$DE_WEEK.$DE_DAYWEEK/$DE_HH" > /etc/TZ

fi


exit 0
}


main_stop()
{
STD=`rdcsman 0x00070001 str` #CSID_C_NTP_TZ_ENVAR
echo "$STD" > /etc/TZ
exit 0
}

#### main ####
[ -z "$1" ] && usage
case "$1" in
# append daylight saving rule to /etc/TZ
  start)
	main_start
    echo
    ;;
# recover the /etc/TZ
  stop)
	main_stop
    echo
    ;;
  *)
    echo "Usage:"
    echo "start: set-dstNTP start"
    echo "stop:  set-dstNTP stop"
    exit 1
esac

exit 0
