/* 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 <assert.h>
#include <locale.h>
#include <libintl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <rpcsvc/nis.h>
#include "nis_xdr.h"
#include "nisd.h"
#include "log_msg.h"

#ifndef _
#define _(String) gettext (String)
#endif

bool_t
nis_mkdir_3_r (nis_name *argp, nis_error *result, struct svc_req *rqstp)
{
  bool_t retval = TRUE;
  struct sockaddr_in *rqhost;
  SERVER_CLOCK_DECLS;
  char *principal;

  start_clock (SERVER_CLOCK);

  principal = get_nis_principal (rqstp);

  if (verbose)
    {
      rqhost = svc_getcaller (rqstp->rq_xprt);
      log_msg (LOG_DEBUG, "nis_mkdir_3() [From: %s:%d,%s]",
	       inet_ntoa (rqhost->sin_addr),
	       ntohs (rqhost->sin_port),principal ? principal : "{error}");

      log_msg (LOG_DEBUG, "\t\tCreate : \"%s\"", *argp);
    }

  if (readonly)
    {
      *result = NIS_TRYAGAIN;
      goto bailout;
    }

  /* We should never see an indexed name. */
  if (strchr (*argp, '[') != NULL)
    {
      *result = NIS_BADNAME;
      goto bailout;
    }

  /* Do some sanity checks */
  *result = nis_validname (*argp);
  if (*result != NIS_SUCCESS)
    goto bailout;

  /* Can only create the directory if we serve it. */
  *result = nis_dcache_lookup (*argp, LOOKUP_ONLY | CHECK_SERVER,
			       MASTER_ONLY, NULL);
  if (*result != NIS_SUCCESS)
    goto bailout;

  /* XXX Check for access rights */
  /* XXX Not thread safe */
  *result = db2nis_error (db_create_dir (nis_name_of (*argp)));
  if (*result != NIS_SUCCESS)
    goto bailout;

  *result = add_to_srvlist (*argp);

 bailout:
  free (principal);

  if (verbose)
    log_msg (LOG_DEBUG, "\tresult = %s", nis_sperrno (*result));

  nis_update_stats (NIS_MKDIR, *result == NIS_SUCCESS ? TRUE : FALSE,
                    stop_clock (SERVER_CLOCK));

  return retval;
}
