#ifndef __INCLUDED_CONFGET_PCRE_H
#define __INCLUDED_CONFGET_PCRE_H

/*-
 * SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <pcre.h>

#define var_pcre	pcre

static void _do_pcre_compile(const char * const pattern, const pcre ** const pvar,
		const pcre_extra ** const pvar_extra, const char * const name,
		const bool is_utf8)
{
	const char *err;
	int ofs;

	pcre * const res = pcre_compile(pattern, is_utf8 ? PCRE_UTF8 : 0,
	    &err, &ofs, NULL);
	if (res == NULL)
		errx(1, "Invalid match %s: %s", name, err);
	*pvar = res;

	pcre_extra * const res_extra = pcre_study(res, 0, &err);
	if (res_extra == NULL)
		errx(1, "Invalid match %s: %s", name, err);
	*pvar_extra = res_extra;
}

static bool _do_pcre_match(const pcre * const var, const pcre_extra * const var_extra,
		const char * const value, const char * const pattern)
{
	const int r = pcre_exec(var, var_extra, value, strlen(value), 0, 0, NULL, 0);
	switch (r) {
		case 0:
			return true;

		case PCRE_ERROR_NOMATCH:
			return false;

		default:
			errx(1, "Could not match '%s' against the '%s' pattern", value, pattern);
	}
}

#define do_pcre_compile(pattern, var, var_extra, name, is_utf8) \
	_do_pcre_compile((pattern), (var), (var_extra), (name), (is_utf8))

#define do_pcre_match(var, var_extra, value, pattern)	\
	_do_pcre_match((var), (var_extra), (value), (pattern))

#define CONFGET_REGEX_IMPL_PCRE_(major, minor) #major "." #minor
#define CONFGET_REGEX_IMPL_PCRE(major, minor) CONFGET_REGEX_IMPL_PCRE_(major, minor)

#endif
