/*
 *   NVRAM WakeUp
 *   Copyright (C) 2001-2003, Sergei Haller.
 *
 *   $Id: gmt-test.c 762 2004-07-21 12:19:57Z bistr-o-math $
 *
 *   Contributed by Dr. Werner Fink <werner@suse.de>
 *   Added some changes/speedups by Dr. Werner Fink and me.
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#define CVSREV_gmt_test_c \
     "$Id: gmt-test.c 762 2004-07-21 12:19:57Z bistr-o-math $"

#include <time.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <syslog.h>
#include <stdlib.h>

#include "nvram-wakeup.h"

int compare_ltm_rtc(void)
{
     /*  The size of `struct tm' is bigger than the size of `struct rtc_time'. */
     /*  Nevertheless, the first 9 entries DO have the same size and the same  */
     /*  meaning. We don't use other entries.                                  */
     /*  Thus we just use the same part of the memory instead of using memcpy. */
     struct tm           rtc;
     struct rtc_time     *rtc_tm = (struct rtc_time *)(void *)(&rtc);

     time_t              diff;

     /* fd_rtc should have been opened by main */
     if (ioctl(fd_rtc, RTC_RD_TIME, rtc_tm) == -1) {
          nvprintf(LOG_ERR, "%s: %m\n", "ioctl RTC_RD_TIME");
          return -2;
     }

     nvprintf(LOG_DEBUG, "Hardware clock: %4d-%02d-%02d %02d:%02d:%02d\n",
                         rtc.tm_year+1900, rtc.tm_mon+1, rtc.tm_mday,
                         rtc.tm_hour,      rtc.tm_min,   rtc.tm_sec  );


     rtc.tm_isdst = -1; /* we don't know if DST is active */

     diff = time(NULL) - mktime(&rtc);

     nvprintf(LOG_DEBUG, "rtc.tm_isdst : %d\n", rtc.tm_isdst);
     nvprintf(LOG_DEBUG, "rtc.tm_gmtoff: %d\n", rtc.tm_gmtoff);

     nvprintf(LOG_DEBUG, "diff         : %d\n", diff);

/*
 *   Test if diff is zero or equal to the value of timezone
 *   (which should be if RTC time is synchronously with system time ...
 *   nevertheless we allow an offset of 5 minutes.)
 */

     /* RTC time is running in UTC or                            */
     /* RTC time is running in localtime (which _is_ UTC)        */
     if (abs(diff-rtc.tm_gmtoff) < 5*60)
     	return 1;
    
     /* RTC time is running in localtime (which is _not_ UTC)    */
     if (abs(diff) < 5*60)
          return 0;

     /* RTC time is not synchronously with system time           */
     return -1;
}
