/*
 * tools/lib/vg_extend_reduce.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * April 1997
 * January 1999
 * 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
 *
 *    26/01/1999 - made volume group directory prefix a preprocessor option
 *    08/02/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>

/* module internal prototype */
int vg_extend_reduce ( char *, pv_t *, vg_t *, int);


inline int vg_extend ( char *vg_name, pv_t *pv, vg_t *vg) {
   return vg_extend_reduce ( vg_name, pv, vg, VG_EXTEND);
}


inline int vg_reduce ( char *vg_name, pv_t *pv, vg_t *vg) {
   return vg_extend_reduce ( vg_name, pv, vg, VG_REDUCE);
}


int vg_extend_reduce ( char *vg_name, pv_t *pv, vg_t *vg, int cr) {
   int group = -1;
   int ret = 0;
   char group_file[NAME_LEN];

#ifdef DEBUG
   debug_enter ( "vg_extend_reduce -- CALLED\n");
#endif

   if ( vg_name == NULL ||
        vg_check_name ( vg_name) < 0 ||
        pv == NULL ||
        vg == NULL ||
        pv_check_consistency ( pv) < 0 ||
        vg_check_consistency_with_pv_and_lv ( vg) < 0) ret = -LVM_EPARAM;
   else {
      sprintf ( group_file, LVM_DIR_PREFIX "%s/group%c", vg_name, 0);
      if ( ( group = open ( group_file, O_RDWR)) == -1)
         ret = -LVM_EVG_EXTEND_REDUCE_OPEN;
      else {
#ifdef DEBUG
         debug ( "vg_extend_reduce -- IOCTL\n");
#endif
         if ( cr == VG_EXTEND) ret = ioctl ( group, cr, pv);
         else                  ret = ioctl ( group, cr, pv->pv_name);
         if ( ret == -1) ret = -errno;
      }
   
      if ( group != -1) close ( group);
#ifdef DEBUG
      debug ( "vg_extend_reduce -- IOCTL returned: %d\n", ret);
#endif
      if ( ret == 0 && cr == VG_REDUCE)
         ret = pv_change_all_pv_of_vg ( vg_name, vg);
   }

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