#include "common.h"
#include "config.h"
#include "fpga.h"

void print_time(const char *msg, const struct timeval *tv)
{
    const struct tm *tm = localtime(&tv->tv_sec);
    char tb1[48], tb2[16];

    strftime(tb1, sizeof tb1, "%a %Y-%m-%d %H:%M:%S", tm);
    strftime(tb2, sizeof tb2, "%z (%Z)", tm);

    printf("%s%s.%03lu %s\n", msg, tb1, tv->tv_usec/1000UL, tb2);
}

volatile bool time_net_sync_status;
void time_net_sync(const struct timeval *tv)
{
    bool synced = !!tv;

    if (synced != time_net_sync_status) {
	time_net_sync_status = synced;
	setvar_bool(status_net_sntp_sync, synced);
	if (!synced) {
	    printf("[SNTP] Time synchronization lost\n");
	} else {
	    print_time("[SNTP] Time synchronized: ", tv);
	}
    }

    if (synced)
      fpga_timesync_trigger();	/* Push time downstream to FPGA/RTC */
}
