/*
 * tools/lib/vg_read.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * March,October,November 1997
 * June,August 1998
 * January 1999
 *
 *
 * 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
 *
 *    08/11/1997 - removed setting PV-pointer in vg_read
 *    29/08/1998 - seperated disk and core structures in vg_read()
 *                 by using vg_copy_from_disk()
 *    15/01/1999 - hand back VG pointer in vg_read() in case of exported VG
 *
 */

#include <liblvm.h>


int vg_read ( char *vg_name, vg_t **vg) {
   int p = 0;
   int pv_handle = -1;
   int ret = 0;
   static vg_disk_t vg_this;
   pv_t **pv = NULL;

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

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

   if ( ( ret = pv_read_all_pv_of_vg ( vg_name, &pv, FALSE)) < 0) {
#ifdef DEBUG
      debug ( "vg_read -- pv_read_all_pv_of_vg returned: %d\n", ret);
#endif
      return ret;
   }

   if ( pv != NULL && pv[0] != NULL) {
#ifdef DEBUG
      if ( opt_d > 0) {
         for ( p = 0; pv[p] != NULL; p++)
            printf ( "vg_read -- pv[%d]->pv_name: \"%s\"\n", p, pv[p]->pv_name);
      }
#endif
   
      /* read the VG info */
      if ( ( pv_handle = open ( pv[0]->pv_name, O_RDONLY)) == -1)
         ret = -LVM_EVG_READ_OPEN;
      else if ( lseek ( pv_handle, pv[0]->vg_on_disk.base, SEEK_SET) != 
                pv[0]->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;
      if ( pv_handle != -1) close ( pv_handle);
   
      *vg = vg_copy_from_disk ( &vg_this);
      if ( (*vg)->vg_status & VG_EXPORTED) ret = -LVM_EVG_READ_VG_EXPORTED;
   
      if ( ret == 0) {
         if ( pv != NULL) for ( p = 0; pv[p] != NULL; p++) {
            if ( pv[p]->version != LVM_STRUCT_VERSION) {
               ret = -LVM_EVG_READ_LVM_STRUCT_VERSION;
               break;
            }
         }
      }
   } else ret = -LVM_EVG_READ_PV;

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

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