/*
 * tools/lib/lv_write.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * March 1997
 * August 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
 *
 */

/*
 * Changelog
 *
 * 30/08/1998 - seperated disk and core lv structures in lv_write()
 *              and lv_write_all_lv_of_vg() by using lv_copy_to_disk()
 *
 */

#include <liblvm.h>


int lv_write ( char *pv_name, vg_t *vg, lv_t *lv, int l) {
   int pvol = -1;
   int ret  = 0;
   lv_disk_t *lv_disk = NULL;

#ifdef DEBUG
   debug ( "lv_write -- CALLED with pv_name: %s  vg->vg_name: %s  "
            "lv->lv_name: %s  index: %d\n",
            pv_name, vg->vg_name, lv->lv_name, l);
#endif

   if ( pv_name == NULL ||
        pv_check_name ( pv_name) < 0 ||
        vg == NULL ||
        lv == NULL ||
        vg->lv_max == 0 ||
        lv_check_consistency ( lv) < 0) return -LVM_EPARAM;

   lv_disk = lv_copy_to_disk ( lv);

   if ( ( pvol = open ( pv_name, O_WRONLY)) == -1)
      ret = -LVM_ELV_WRITE_OPEN;
   else if ( lseek ( pvol,
                     LVM_LV_DISK_OFFSET (
                        vg->pv[pv_get_index_by_name ( vg, pv_name)], l),
                     SEEK_SET) != LVM_LV_DISK_OFFSET ( vg->pv[0], l))
      ret = -LVM_ELV_WRITE_LSEEK;
   else if ( write ( pvol, lv_disk, sizeof ( lv_disk_t)) != sizeof ( lv_disk_t))
      ret = -LVM_ELV_WRITE_WRITE;

   if ( pvol != -1) {
      fsync ( pvol);
      close ( pvol);
   }
   free ( lv_disk);

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