/* vim:ts=4:sts=4:sw=4:et:cindent
 * datefudge.c: Twist system date back N seconds
 *
 * Copyright (C) 2001-2003, Matthias Urlichs <smurf@noris.de>
 * Copyright (C) 2008-2011, Robert Luberda <robert@debian.org>
 *
 */
#define _GNU_SOURCE

#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <assert.h>
#include <features.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>

#ifdef __CYGWIN__
#include <sys/cygwin.h>
void *RTLD_NEXT = NULL;
#endif

static int fudge = 0;
static int dostatic = 0;

static void init_fudge (void) {
    const char *fud;

    if(fudge)return;

    fud = getenv("DATEFUDGE");
    if(fud == NULL) return;
    fudge = atoi(fud);
    dostatic = getenv("DATEFUDGE_DOSTATIC") != NULL;
}

static void set_fudge(time_t *seconds)
{
    if (!seconds)
        return;

    init_fudge();

    if (dostatic)
        *seconds = fudge;
    else
        *seconds -= fudge;
}

#ifndef __GNU__

time_t time(time_t *x) {
    static time_t (*libc_time)(time_t *) = NULL;
    time_t res;

#ifdef __CYGWIN__
    if(!RTLD_NEXT)
        RTLD_NEXT = dlopen("cygwin1.dll", 0);
#endif
    if(!libc_time)
        libc_time = (typeof(libc_time))dlsym (RTLD_NEXT, __func__);
    res = (*libc_time)(x);
    set_fudge(x);
    set_fudge(&res);
    return res;
}

#endif

int gettimeofday(struct timeval *x, void *y) {
    static int (*libc_gettimeofday)(struct timeval *, void *) = NULL;
    int res;

#ifdef __CYGWIN__
    if(!RTLD_NEXT)
        RTLD_NEXT = dlopen("cygwin1.dll", 0);
#endif
    if(!libc_gettimeofday)
        libc_gettimeofday = (typeof(libc_gettimeofday))dlsym (RTLD_NEXT, __func__);
    res = (*libc_gettimeofday)(x,y);
    if(res) return res;
    set_fudge(&x->tv_sec);
    return 0;
}

#ifndef __GNU__

int clock_gettime(clockid_t x, struct timespec *y) {
    static int (*libc_clock_gettime)(clockid_t, struct timespec*);
    int res;

#ifdef __CYGWIN__
    if(!RTLD_NEXT)
        RTLD_NEXT = dlopen("cygwin1.dll", 0);
#endif
    if (!libc_clock_gettime)
        libc_clock_gettime =  (typeof(libc_clock_gettime))dlsym (RTLD_NEXT, __func__);
    res = (*libc_clock_gettime)(x,y);
    if (res || CLOCK_REALTIME != x) return res;
    set_fudge(&y->tv_sec);
    return 0;
}

#endif

#ifdef __CYGWIN__

__attribute__((constructor))
void _init (void)
{
  cygwin_internal (CW_HOOK, "time", time);
  cygwin_internal (CW_HOOK, "gettimeofday", gettimeofday);
  cygwin_internal (CW_HOOK, "clock_gettime", clock_gettime);
}

#endif
