/*
 * tools/lib/pv_write.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * August-September 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
 *
 *    30/08/1998 - seperated disk and core pv structure in pv_write()
 *                 by using pv_copy_to_disk()
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    22/03/2000 - autocreate physical volume UUID
 *
 */

#include <liblvm.h>


int pv_write ( char *pv_name, pv_t *pv) {
   int pv_handle = -1;
   int ret = 0;
   pv_disk_t *pv_disk = NULL;

#ifdef DEBUG
   debug_enter ( "pv_write -- CALLED with %s %X\n", pv_name, (uint) pv);
#endif

   if ( pv_name == NULL ||
        pv_check_name ( pv_name) < 0 ||
        pv == NULL ||
        pv_check_consistency ( pv) < 0) ret = -LVM_EPARAM;
   else {
      if ( lvm_check_uuid ( pv->pv_uuid) < 0) {
         memset ( pv->pv_uuid, 0, sizeof ( pv->pv_uuid));
         memcpy ( pv->pv_uuid,
                   lvm_create_uuid(UUID_LEN),
                   sizeof(pv->pv_uuid)-1);
      }

      /* convert core to disk data */
      pv_disk = pv_copy_to_disk ( pv);
      if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1)
         ret = -LVM_EPV_WRITE_OPEN;
      else if ( lseek ( pv_handle, pv->pv_on_disk.base, SEEK_SET) !=
                pv->pv_on_disk.base) ret = -LVM_EPV_WRITE_LSEEK;
      else if ( write ( pv_handle, pv_disk,
                        sizeof ( pv_disk_t)) != sizeof ( pv_disk_t))
         ret = -LVM_EPV_WRITE_WRITE;
      free ( pv_disk);
   
      if ( pv_handle != -1) {
         fsync ( pv_handle);
         close ( pv_handle);
      }
   }

#ifdef DEBUG
   debug_leave ( "pv_write -- LEAVING\n");
#endif
   return ret;
}
