/*
 * tools/lib/lv_read_byindex.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * May,August,December 1998
 * 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
 *
 *    31/01/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>


int lv_read_byindex ( char *vg_name, ulong lv_index, lv_t **lv) {
   int ret = 0;
   ulong l = 0;
   static lv_t lv_this;
   lv_t **lv_this_ptr;
   vg_t *vg_this = NULL;
   vg_t vg_this_sav;

   debug_enter ( "lv_read_byindex-- CALLED with: \"%s\" %d %X\n",
                 vg_name, lv_index, ( uint) lv);

   if ( vg_name == NULL || lv == NULL ||
        vg_check_name ( vg_name) < 0) {
      ret = -LVM_EPARAM;
      goto lv_read_byindex_end;
   }

   *lv = NULL;

   if ( ( ret = vg_read ( vg_name, &vg_this)) < 0 &&
        ret != -LVM_EVG_READ_VG_EXPORTED) {
      ret = -LVM_ELV_READ_BYINDEX_VG_READ;
      goto lv_read_byindex_end;
   }
   if ( lv_index > vg_this->lv_max - 1) {
      ret = -LVM_EPARAM;
      goto lv_read_byindex_end;
   }

   memcpy ( &vg_this_sav, vg_this, sizeof ( vg_t));
   vg_this = &vg_this_sav;
   debug ( "lv_read_byindex-- BEFORE lf_read_all_lv_of_vg\n");
   if ( ( ret = lv_read_all_lv ( vg_name, &lv_this_ptr, FALSE)) < 0) {
      ret = -LVM_ELV_READ_BYINDEX_LV_READ_ALL_LV;
      goto lv_read_byindex_end;
   }

   ret = -LVM_ELV_READ_LV;
   for ( l = 0; l < vg_this->lv_max; l++) {
      if ( lv_this_ptr[l] != NULL) {
         if ( lv_this_ptr[l]->lv_number == lv_index) {
            ret = 0;
            break;
         }
      }
   }
   if ( ret == 0) {
      if ( strcmp ( lv_this_ptr[lv_index]->vg_name, vg_name) != 0)
         ret = -LVM_ELV_READ_BYINDEX_VG_NAME;
      else {
         memcpy ( &lv_this, lv_this_ptr[l], sizeof ( lv_t));
         *lv = &lv_this;
         ret = 0;
      }
   }

lv_read_byindex_end:

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