/*
 * dbmatch.c  -  Match database section names
 *
 * Copyright (C) 2006-2007 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: dbmatch.c,v 1.2 2007/01/06 18:31:38 gkminix Exp $
 */

#include <common.h>
#include <nblib.h>
#include "privlib.h"
#include "privdb.h"



/*
 * Match a database record name against a string. This routine
 * works pretty much the same as the fnmatch() function in the
 * standard C library: '*' means to match any sequence of charac-
 * ters, and '?' means to match exactly one character. However,
 * character classes are not supported because they are diffi-
 * cult to map onto the underlying database search routines.
 */
int nblib_db_match __F((pattern, string),
				const char *pattern AND
				const char *string)
{
  register const char *p = pattern, *n = string;
  register char c;

  while ((c = *p++) != '\0') {
	switch (c) {
		case DBMATCH_SINGLE:
			/*
			 * For matching a single character, just move the
			 * string pointer one step forward. However, we
			 * don't match the end of the string.
			 */
			if (*n == '\0')
				return(FALSE);
			break;

		case DBMATCH_MULTI:
			/*
			 * Scan through the pattern to find any additional
			 * wildcard characters in a row.
			 */
			c = *p++;
			while (c == DBMATCH_SINGLE || c == DBMATCH_MULTI) {
				if (c == DBMATCH_SINGLE && *n++ == '\0')
					return(FALSE);
				c = *p++;
			}

			/*
			 * If we reached the end of the pattern, there is
			 * no need to scan any further, because all the rest
			 * of the string gets matched.
			 */
			if (c == '\0')
				return(TRUE);

			/*
			 * Now match the rest of the string recursively. We
			 * can be sure that the pattern pointer shows to a
			 * non-wildcard character.
			 */
			for (p--; *n != '\0'; n++) {
				if (*n == c && nblib_db_match(p, n))
					return(TRUE);
			}
			return(FALSE);

		default:
			/*
			 * For any other pattern character, we simply compare
			 * the pattern with the string.
			 */
			if (c != *n)
				return(FALSE);
	}
	n++;
  }

  /* Check if we are at the end of the string */
  return(*n == '\0');
}

