/*
 * tools/lib/pv_write_uuidlist.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * August-September 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
 *
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    17/03/2000 - changed namelist to uuidlist
 *
 */
  
#include <liblvm.h>


int pv_write_uuidlist ( char *pv_name, vg_t *vg) {
   int p = 0, pp = 0;
   int pv_handle = -1;
   int ret = 0;
   int size = 0;
   char *pv_uuid_list = NULL;

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

   if ( pv_name == NULL || pv_check_name ( pv_name) < 0 ||
        vg == NULL || vg_check_name ( vg->vg_name) < 0) ret = -LVM_EPARAM;
   else if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1)
      ret = -LVM_EPV_WRITE_UUIDLIST_OPEN;
   else if ( lseek ( pv_handle, vg->pv[0]->pv_uuidlist_on_disk.base,
                     SEEK_SET) != vg->pv[0]->pv_uuidlist_on_disk.base)
      ret = -LVM_EPV_WRITE_UUIDLIST_LSEEK;
   else {
      size = vg->pv_max * NAME_LEN;
      if ( ( pv_uuid_list = malloc ( size)) == NULL) {
         fprintf ( stderr, "malloc error in %s [line %d]\n",
                           __FILE__, __LINE__);
         ret = LVM_EPV_WRITE_UUIDLIST_MALLOC;
      } else {
         memset ( pv_uuid_list, 0, size);
         for ( p = 0; p < vg->pv_max; p++) {
            if ( vg->pv[p] != NULL) {
               strncpy ( &pv_uuid_list[pp*NAME_LEN],
                         vg->pv[p]->pv_uuid,
                         UUID_LEN);
               pp++;
            }
         }
         if ( write ( pv_handle, pv_uuid_list, size) != size)
            ret = -LVM_EPV_WRITE_UUIDLIST_WRITE;
         free ( pv_uuid_list);
      }
   }

   if ( pv_handle != -1) {
      fsync ( pv_handle);
      close ( pv_handle);
   }

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