#!/bin/sh

if [ ! -x /sbin/hwclock ]
then
    exit 0
fi

if [ "$1" = "start" ]
then
    export TZ=UTC
    echo "Adjust system time"
    # Set system time from hardware clock
    hwclock --hctosys

    # Read time offset [in seconds - could be negative]
    TIME_OFFSET_FILE="/etc/time_offset"
    
    if [ ! -f "$TIME_OFFSET_FILE" ]; then
        touch $TIME_OFFSET_FILE
        chown root:gr_webserver $TIME_OFFSET_FILE
        chmod 0660 $TIME_OFFSET_FILE
        exit 0
    fi
    
    if [ -s "$TIME_OFFSET_FILE" ]; then

        TIME_OFFSET=`cat $TIME_OFFSET_FILE`
        
        # Check if offset is an integer
        if [ "`expr \"$TIME_OFFSET\" : \"\-\?[0-9]\+\"`" != "0" ]; then
            # Current system time in seconds
            CURRENT_TIME=`date +%s`
            NEW_TIME=`expr $CURRENT_TIME + $TIME_OFFSET`
            NEW_TIME_FORMATTED=`date -d @$NEW_TIME +"%Y-%m-%d %H:%M:%S"`
            # Set new system time
            ERRTEXT=`date -s "$NEW_TIME_FORMATTED"`
            if [ $? -ne 0 ]; then
                echo $ERRTEXT
            fi
        else
            echo "time offset value is not a number: '$TIME_OFFSET'"
        fi
    fi
fi

#if [ "$1" = "stop" -o "$1" = "restart" ]
#then
#    if [ -x /sbin/hwclock ]
#    then
#        echo "Syncing hardware clock to system time"
#        /sbin/hwclock -w
#    fi
#fi
#
#if [ "$1" = "start" -o "$1" = "restart" ]
#then
#    if [ -x /bin/ntpclient -a "$NTP_SERVER" ]
#    then
#        echo "Setting time from ntp server: $NTP_SERVER"
#        /bin/ntpclient -s -c 2 -i 3 -h $NTP_SERVER >/dev/null
#    else
#        if [ ! -f /etc/setttime_msg ]
#        then
#            echo "Please set the system time using"
#            echo "    date <mmddhhmnyyyy>"
#            echo "    /sbin/hwclock -w"
#            touch /etc/setttime_msg
#            sleep 2
#        fi
#    fi
#fi
