#include <stdio.h>
#include <rtos.h>
#include <net.h>
#include <time.h>
#include <dos.h>

/* Notes:
 * The time is the number of seconds since 00:00 (midnight) 1 January 1900
 * GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; this
 * base will serve until the year 2036.
 *
 * For example:
 *     2,208,988,800L corresponds to 00:00  1 Jan 1970 GMT, start of UNIX time
 */

#define TIME_PORT 37
#define BASE_TIME 2208988800L

/*
 * ntime() given the host address, returns Unix styled TIME.
 */

DWORD ntime(DWORD host)
{
    tcp_Socket *s;
    int status;
    long temptime;

    s = kcalloc( sizeof( tcp_Socket ), 1 );
    if (s == NULL ) return( 0 );

    status = 0;
    temptime = 0L;

    if ( tcp_open( s, 0, host, TIME_PORT, NULL )) {
        sock_wait_established(s, sock_delay , NULL, &status);

        while ( 1 ) {
            sock_tick( s, &status );

            if (sock_dataready( s ) >= 4 ) {
                sock_read( s, (void *)&temptime, sizeof( long ));

                temptime = ntohl( temptime );       /* convert byte orderring */
                temptime -= BASE_TIME;
sock_err:
                sock_close( s );
                while ( tcp_tick( s ) ) rt_sleep( 10 );
                break;
            }
	}
    }
    kfree( s );
    return( temptime );
}

void nsettime( DWORD host )
{
    DWORD t;
    struct time tm;
    struct date da;

    if ( ( t = ntime( host )) > 0 ) {
        dos_enter();
        /* this will set the date, but the time will be overwritten by eRTOS */
        stime( &t );

        unixtodos( t, &da, &tm );
        rt_settime( &tm );
        dos_exit();
    }
}

