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

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

static time_t fudge = 0;
static bool dostatic = false;
static bool fudge_set = false;

static void init_fudge(void) {
  const char *const fud = getenv("DATEFUDGE");

  if (fud == NULL)
    return;

  if (sizeof(time_t) <= sizeof(int))
    fudge = atoi(fud);
  else
    fudge = atoll(fud);

  dostatic = getenv("DATEFUDGE_DOSTATIC") != NULL;
  fudge_set = true;
}

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

  if (!fudge_set)
    init_fudge();

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

/* Note: a macro, because subseconds can be timeval.tv_usec or timespec.tv_nsec,
 * that might be of different types */
#define SET_FUDGE_WITH_SUBSECS(seconds, subseconds)                            \
  do {                                                                         \
    set_fudge(&seconds);                                                       \
    if (dostatic)                                                              \
      subseconds = 0;                                                          \
  } while (false)

time_t time(time_t *tloc) {
  static time_t (*libc_time)(time_t *) = NULL;

  if (!libc_time)
    libc_time = (typeof(libc_time))dlsym(RTLD_NEXT, __func__);

  time_t res = (*libc_time)(tloc);
  set_fudge(tloc);
  set_fudge(&res);
  return res;
}

int gettimeofday(struct timeval *tv, void *tz) {
  static int (*libc_gettimeofday)(struct timeval *, void *) = NULL;

  if (!libc_gettimeofday)
    libc_gettimeofday = (typeof(libc_gettimeofday))dlsym(RTLD_NEXT, __func__);

  const int res = (*libc_gettimeofday)(tv, tz);
  if (res)
    return res;

  SET_FUDGE_WITH_SUBSECS(tv->tv_sec, tv->tv_usec);
  return 0;
}

int clock_gettime(clockid_t clockid, struct timespec *tp) {
  static int (*libc_clock_gettime)(clockid_t, struct timespec *) = NULL;

  if (!libc_clock_gettime)
    libc_clock_gettime = (typeof(libc_clock_gettime))dlsym(RTLD_NEXT, __func__);

  const int res = (*libc_clock_gettime)(clockid, tp);
  if (res || clockid != CLOCK_REALTIME)
    return res;

  SET_FUDGE_WITH_SUBSECS(tp->tv_sec, tp->tv_nsec);
  return 0;
}
