// Copyright © 2024 Haelwenn (lanodan) Monnier <contact@hacktivis.me>
// SPDX-License-Identifier: MIT
#define _GNU_SOURCE // program_invocation_name

#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "error.h"

unsigned int error_message_count = 0;
void (*error_print_progname)(void) = NULL;
int error_one_per_line = 0;

void
error(int status, int errnum, const char *format, ...)
{
	fflush(stdout);

	if(error_print_progname != NULL)
	{
		(*error_print_progname) ();
	}
	else
	{
		fprintf(stderr, "%s:", program_invocation_name);
	}

	va_list args;
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);

	if(errnum != 0)
		fprintf(stderr, ": %s", strerror(errnum));

	putc('\n', stderr);

	error_message_count++;

	if(status != 0) exit(status);
}

void
error_at_line(int status, int errnum, const char *filename, unsigned int linenum, const char *format, ...)
{
	if(error_one_per_line != 0)
	{
		static const char *prev_filename;
		static unsigned int prev_linenum;

		if(prev_linenum == linenum &&
			(prev_filename == filename || strcmp(prev_filename, filename) == 0)
		) return; // already printed, skip

		prev_filename = filename;
		prev_linenum = linenum;
	}

	fflush(stdout);

	if(error_print_progname != NULL)
	{
		(*error_print_progname) ();
	}
	else
	{
		fprintf(stderr, "%s:", program_invocation_name);
	}

	fprintf(stderr, " %s:%d: ", filename, linenum);

	va_list args;
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);

	if(errnum != 0)
		fprintf(stderr, ": %s", strerror(errnum));

	putc('\n', stderr);

	error_message_count++;

	if(status != 0) exit(status);
}
