// version 20230126
// public domain
// djb

// automatic-alternatives 1 getrandom_wrapper.o getentropy_wrapper.o devurandom_wrapper.o

#include <unistd.h>
#include "getrandom_wrapper.h"
#include "getentropy_wrapper.h"
#include "devurandom_wrapper.h"
#include "randombytes.h"

static enum {
  use_nothing,
  use_getrandom,
  use_getentropy,
  use_devurandom
} use = use_nothing;

__attribute__((constructor))
static void startup(void)
{
  if (getrandom_wrapper_ready())  { use = use_getrandom;  return; }
  if (getentropy_wrapper_ready()) { use = use_getentropy; return; }
  if (devurandom_wrapper_ready()) { use = use_devurandom; return; }
}

void randombytes(void *x,long long xbytes)
{
  if (use == use_getrandom)  { getrandom_wrapper(x,xbytes);  return; }
  if (use == use_getentropy) { getentropy_wrapper(x,xbytes); return; }
  if (use == use_devurandom) { devurandom_wrapper(x,xbytes); return; }
  for (;;) pause();
}

const char *randombytes_source(void)
{
  if (use == use_getrandom)  return "kernel-getrandom";
  if (use == use_getentropy) return "kernel-getentropy";
  if (use == use_devurandom) return "kernel-devurandom";
  return "kernel-nothing";
}
