/*
 * tools/lib/vg_read_from_pv.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * April 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
 *
 */

#include <liblvm.h>


int vg_read_from_pv ( char *pv_name, vg_t **vg) {
   int pv_handle = -1;
   int ret = 0;
   static vg_disk_t vg_this;
   pv_t pv_this;
   pv_t *pv_this_ptr = &pv_this;

   debug_enter ( "vg_read_from_pv -- CALLED\n");

   if ( pv_name == NULL ||
        pv_check_name ( pv_name) < 0 ||
        vg == NULL) {
      ret = -LVM_EPARAM;
      goto vg_read_from_pv_end;
   }

   if ( ( ret = pv_read ( pv_name, &pv_this_ptr, NULL)) == 0 ||
	   ret == -LVM_EPV_READ_MD_DEVICE ||
	   ret == -LVM_EPV_READ_PV_EXPORTED) {
      /* read the VG info */
      if ( ( pv_handle = open ( pv_name, O_RDONLY)) == -1)
         ret = -LVM_EVG_READ_OPEN;
      else if ( lseek ( pv_handle, pv_this_ptr->vg_on_disk.base, SEEK_SET) != 
                pv_this_ptr->vg_on_disk.base) ret = -LVM_EVG_READ_LSEEK;
      else if ( read ( pv_handle, &vg_this, sizeof ( vg_this)) != \
                sizeof ( vg_this)) ret = -LVM_EVG_READ_READ;
      else ret = 0;
      if ( pv_handle != -1) close ( pv_handle);
   
      if ( ret == 0) {
         *vg = vg_copy_from_disk ( &vg_this);
         strncpy ( (*vg)->vg_name, pv_this_ptr->vg_name,
                   sizeof ( (*vg)->vg_name));
         if ( (*vg)->vg_status & VG_EXPORTED) ret = -LVM_EVG_READ_VG_EXPORTED;
         else if (!lvm_pv_check_version(pv_this_ptr)) {
            ret = -LVM_EVG_READ_LVM_STRUCT_VERSION;
         }
      }
   } else ret = -LVM_EVG_READ_PV;

   if ( ret != 0 && ret != -LVM_EVG_READ_VG_EXPORTED) *vg = NULL;

vg_read_from_pv_end:

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