/* Copyright (c) 1999 Thorsten Kukuk
   Author: Thorsten Kukuk <kukuk@suse.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, or (at your option)
   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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <unistd.h>
#include <rpc/rpc.h>
#include <rpcsvc/nis.h>

#include "nis_db.h"
#include "db_private.h"

db_status
db_create_table (const char *table_name, const table_obj *table)
{
 table_t *t_entry;
 char *curdir, *cp;
 int is_searchable = 0;
 u_int i;

 /* A table name is not a file name. Don't allow fully qualified paths. */
  if (strchr (table_name, '/'))
    return DB_BADQUERY;

  if (db_table_exists (table_name) == DB_SUCCESS)
    return DB_NOTUNIQUE;

  /* Check that at least one column is searchable. */
#define NAME table->ta_cols.ta_cols_val[i].tc_name
  for (i = 0; i < table->ta_cols.ta_cols_len; ++i)
    if (table->ta_cols.ta_cols_val[i].tc_flags & TA_SEARCHABLE)
      ++is_searchable;

  if (!is_searchable)
    return DB_BADQUERY;

  t_entry = calloc (1, sizeof (table_t));
  if (t_entry == NULL)
    return DB_MEMORY_LIMIT;

  cp = malloc (NIS_MAXNAMELEN + strlen (table_name) + 3);
  if (cp == NULL)
    {
      free (t_entry);
      return DB_MEMORY_LIMIT;
    }

  curdir = getcwd (cp, NIS_MAXNAMELEN);
  if (curdir == NULL)
    {
      free (t_entry);
      free (cp);
      return DB_INTERNAL_ERROR;
    }

  strcat (curdir, "/");
  strcat (curdir, table_name);
  t_entry->hashkey = __nis_hash (table_name, strlen (table_name));
  t_entry->name = strdup (table_name);
  t_entry->path = strdup (curdir);
  t_entry->object = __clone_table (table);
  free (curdir);

  return __add_table (t_entry);
}
