/*
 * tools/lib/pv_read_namelist.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * March-May,October-November 1997
 * May,August,November 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_read_namelist ( char *pv_name, vg_t *vg, char **pv_namelist) {
   int pv_handle = -1;
   int ret = 0;
   static char *this_pv_namelist = NULL;

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

   if ( this_pv_namelist != NULL) {
      free ( this_pv_namelist);
      this_pv_namelist = NULL;
   }

   if ( pv_name == NULL || pv_check_name ( pv_name) < 0 ||
        vg == NULL || vg_check_name ( vg->vg_name) < 0 ||
        vg->pv[0] == NULL || vg->pv[0]->pv_namelist_on_disk.base == 0 ||
        pv_namelist == NULL) return -LVM_EPARAM;

   if ( ( pv_handle = open ( pv_name, O_RDONLY)) == -1)
      ret = -LVM_EPV_READ_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_READ_NAMELIST_LSEEK;
   else {
      if ( ( this_pv_namelist = malloc ( vg->pv_cur * NAME_LEN)) == NULL) {
         fprintf ( stderr, "malloc error in %s [line %d]\n",
                           __FILE__, __LINE__);
         ret = LVM_EPV_READ_NAMELIST_MALLOC;
      } else {
         memset ( this_pv_namelist, 0, vg->pv_cur * NAME_LEN);
         if ( read ( pv_handle, this_pv_namelist, vg->pv_cur * NAME_LEN) !=
              vg->pv_cur * NAME_LEN) {
            free ( this_pv_namelist);
            this_pv_namelist = NULL;
            ret = -LVM_EPV_READ_NAMELIST_READ;
         }
      }
   }

   if ( pv_handle != -1) close ( pv_handle);
   if ( ret == 0) *pv_namelist = this_pv_namelist;

#ifdef DEBUG
   debug ( "pv_read_namelist -- LEAVING with ret: %d\n");
#endif
   return ret;
}
