/*
 * Copyright (c) 2026 Chris Webb <chris@arachsys.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/time.h>
#include <sys/timex.h>
#include <errno.h>

int adjtime(const struct timeval *in, struct timeval *out)
{
	struct timex tx = { 0 };
	if (in) {
		if (in->tv_sec > 1000 || in->tv_usec > 1000000000) {
			errno = EINVAL;
			return -1;
		}
		tx.offset = in->tv_sec*1000000 + in->tv_usec;
		tx.modes = ADJ_OFFSET_SINGLESHOT;
	}
	if (adjtimex(&tx) < 0)
		return -1;
	if (out) {
		out->tv_sec = tx.offset / 1000000;
		if ((out->tv_usec = tx.offset % 1000000) < 0) {
			out->tv_sec--;
			out->tv_usec += 1000000;
		}
	}
	return 0;
}
