#ifndef __INCLUDED_CONFGET_PCRE_H
#define __INCLUDED_CONFGET_PCRE_H

/*-
 * Copyright (c) 2021  Peter Pentchev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#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 char *err;
	int ofs;

	pcre * const res = pcre_compile(pattern, 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) \
	_do_pcre_compile((pattern), (var), (var_extra), (name))

#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
