/*
 * tools/lib/lv_create_node.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * May 1997
 * January 2000
 *
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

/*
 * Changelog
 *
 *    11/01/1998 - added unlink() on logical volume special file
 *    29/04/1998 - added vg_number, lv_number usage to get
 *                 seperation from LV name
 *               - changed to new lv_create_kdev_t()
 *    27/07/1998 - enhanced error check
 *    31/01/2000 - use debug_enter()/debug_leave()
 *    15/02/2001 - don't create device nodes if we're using devfs
 *
 */

#include <liblvm.h>

int lv_create_node ( lv_t *lv) {
   gid_t gid = 0;
   int ret = 0;
   struct group *grent = NULL;

   debug_enter("lv_create_node -- CALLED with %s\n", lv ? lv->lv_name : "NULL");

   if ( lv == NULL || lv_check_consistency ( lv) < 0) {
      ret = -LVM_EPARAM;
      goto lv_create_node_end;
   }

   if (lvm_check_devfs()) {
       ret = 0;
       goto lv_create_node_end;
   }
   
   if ( unlink ( lv->lv_name) == -1) {
      if ( errno != ENOENT) {
         ret = -LVM_ELV_CREATE_NODE_UNLINK;
         goto lv_create_node_end;
      }
   }

   if ( ( grent = getgrnam ( "disk")) != NULL) gid = grent->gr_gid;
   
   if ( mknod ( lv->lv_name, S_IFBLK | S_IRUSR | S_IWUSR | S_IRGRP,
                lv->lv_dev) == -1)
      ret = -LVM_ELV_CREATE_NODE_MKNOD;
   else if ( chmod ( lv->lv_name, 0660) == -1) ret = -LVM_ELV_CREATE_NODE_CHMOD;
   else if ( chown ( lv->lv_name, 0, gid) == -1) ret = -LVM_ELV_CREATE_NODE_CHOWN;

lv_create_node_end:

   debug_leave ( "lv_create_node -- LEAVING with %d\n", ret);
   return ret;
}
