/*
 * tools/lib/pv_write_namelist.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * March 1997
 * August-September 1998
 *
 *
 * 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
 *
 */

#include <liblvm.h>


int pv_write_namelist ( char *pv_name, vg_t *vg) {
   int p = 0;
   int pv_handle = -1;
   int ret = 0;
   int size = 0;
   char *pv_name_list = NULL;

#ifdef DEBUG
   debug ( "pv_write_namelist -- CALLED\n");
#endif

   if ( pv_name == NULL || pv_check_name ( pv_name) < 0 ||
        vg == NULL || vg_check_name ( vg->vg_name) < 0) return -LVM_EPARAM;

   if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1)
      ret = -LVM_EPV_WRITE_NAMELIST_OPEN;
   else if ( lseek ( pv_handle, vg->pv[0]->pv_namelist_on_disk.base,
                     SEEK_SET) != vg->pv[0]->pv_namelist_on_disk.base)
      ret = -LVM_EPV_WRITE_NAMELIST_LSEEK;
   else {
      size = vg->pv_cur * NAME_LEN;
      if ( ( pv_name_list = malloc ( size)) == NULL) {
         fprintf ( stderr, "malloc error in %s [line %d]\n",
                           __FILE__, __LINE__);
         ret = LVM_EPV_WRITE_NAMELIST_MALLOC;
      } else {
         memset ( pv_name_list, 0, size);
         for ( p = 0; p < vg->pv_cur; p++) {
            if ( vg->pv[p] != NULL)
               strcpy ( &pv_name_list[p*NAME_LEN], vg->pv[p]->pv_name);
         }
         if ( write ( pv_handle, pv_name_list, size) != size)
            ret = -LVM_EPV_WRITE_NAMELIST_WRITE;
         free ( pv_name_list);
      }
   }

   if ( pv_handle != -1) {
      fsync ( pv_handle);
      close ( pv_handle);
   }

#ifdef DEBUG
   debug ( "pv_write_namelist -- LEAVING\n");
#endif
   return ret;
}
