#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>

static int (*orig_open)(const char *pathname, int flags, ...);

__attribute__((constructor))
static void constructor() {
  orig_open = dlsym(RTLD_NEXT, "open");
  if (!orig_open)
    abort();
}

int open(const char *file, int oflag, ...) {
  int mode = 0;

  oflag &= ~O_DIRECT;

  if (oflag & O_CREAT) {
    va_list arg;
    va_start(arg, oflag);
    mode = va_arg(arg, int);
    va_end(arg);
  }

  return orig_open(file, oflag, mode);
}

int open64(const char *file, int oflag, ...) {
  int mode = 0;

  oflag |= O_LARGEFILE;
  oflag &= ~O_DIRECT;

  if (oflag & O_CREAT) {
    va_list arg;
    va_start(arg, oflag);
    mode = va_arg(arg, int);
    va_end(arg);
  }

  return orig_open(file, oflag, mode);
}

int __open_2(const char *file, int oflag) {
  return orig_open(file, oflag & ~O_DIRECT, 0);
}

int __open64_2(const char *file, int oflag) {
  return orig_open(file, (oflag & ~O_DIRECT) | O_LARGEFILE, 0);
}
