/*
 * tools/lib/vg_write.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * August,December 1998
 * January,March 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
 *
 *    30/08/1998 - seperated disk and core vg structures in vg_write()
 *                 by using vg_copy_to_disk()
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    28/03/2000 - autocreate volume group UUID
 *
 */

#include <liblvm.h>

int vg_write ( char *pv_name, pv_t *pv, vg_t *vg) {
   int pv_handle = -1;
   int ret = 0;
   vg_disk_t *vg_disk = NULL;

#ifdef DEBUG
   debug_enter ( "vg_write -- CALLED  storing %s on %s\n",
                 vg->vg_name, pv_name);
#endif

   if ( pv_name == NULL ||
        pv_check_name ( pv_name) < 0 ||
        vg == NULL ||
        vg_check_consistency ( vg) < 0) ret = -LVM_EPARAM;
   else {
      if ( lvm_check_uuid ( vg->vg_uuid) < 0) {
         memset ( vg->vg_uuid, 0, sizeof(vg->vg_uuid));
         memcpy ( vg->vg_uuid,
                  lvm_create_uuid(UUID_LEN),
                  sizeof(vg->vg_uuid)-1);
      }
      vg_disk = vg_copy_to_disk ( vg);
      errno = 0;
   
      if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1)
         ret = -LVM_EVG_WRITE_OPEN;
      else if ( lseek ( pv_handle, pv->vg_on_disk.base, SEEK_SET) !=
                        pv->vg_on_disk.base)
         ret = -LVM_EVG_WRITE_LSEEK;
      else if ( write ( pv_handle, vg_disk,
                        sizeof ( vg_disk_t)) != sizeof ( vg_disk_t))
         ret = -LVM_EVG_WRITE_WRITE;
   
#ifdef DEBUG
      debug ( "vg_write -- errno after write: %d\n", errno);
#endif
   
      free ( vg_disk);
   
      if ( pv_handle != -1) {
         fsync ( pv_handle);
         close ( pv_handle);
      }
   }

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