/*
 * tools/vgmerge.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * June,September,December 1998
 * October 1999
 * February 2000
 *
 * LVM is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 * 
 * LVM 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with LVM; see the file COPYING.  If not, write to
 * the Free Software Foundation, 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA. 
 *
 */

/*
 * Changelog
 *
 *    05/09/1998 - corrected some messages
 *    22/12/1998 - fixed PE counter bug
 *                 (pv_check_consistency_all_pv() involved too)
 *    06/10/1999 - implemented support for long options
 *    15/02/2000 - use lvm_error()
 *    23/01/2001 - added call to lvm_init (JT)
 *
 */

#include <lvm_user.h>

char *cmd = NULL;

#ifdef DEBUG
int opt_d = 0;
#endif

int main ( int argc, char **argv) {
   int c = 0;
   int l = 0;
   int np = 0;
   int np_sav = 0;
   int opt_A = 1;
   int opt_A_set = 0;
   int opt_l = 0;
   int opt_t = 0;
   int opt_v = 0;
   int p = 0;
   int pe_allocated_sav = 0;
   int ret = 0;
   int v = 0;
   char *options = "A:h?ltv" DEBUG_SHORT_OPTION;
   struct option long_options[] = {
      { "autobackup", required_argument, NULL, 'A'},
      DEBUG_LONG_OPTION
      { "help",       no_argument,       NULL, 'h'},
      { "list",       no_argument,       NULL, 'l'},
      { "test",       no_argument,       NULL, 't'},
      { "verbose",    no_argument,       NULL, 'v'},
      { NULL,         0,                 NULL, 0},
   };
   char *vg_name_to = NULL;
   char *vg_name_from = NULL;
   vg_t *vg_to = NULL;
   vg_t *vg_from = NULL;
   vg_t vg_to_this;
   vg_t vg_from_this;

   /* lvm_init(argc, argv); */
   cmd = basename ( argv[0]);

   LVMTAB_CHECK;

   while ( ( c = getopt_long ( argc, argv, options,
                               long_options, NULL)) != EOF) {
      switch ( c) {
         case 'A':
	    opt_A_set++;
            if ( opt_A > 1) {
               fprintf ( stderr, "%s -- A option already given\n\n", cmd);
               return LVM_EINVALID_CMD_LINE;
            }
            if ( strcmp ( optarg, "y") == 0);
            else if ( strcmp ( optarg, "n") == 0) opt_A = 0;
            else {
               fprintf ( stderr, "%s -- invalid option argument \"%s\"\n\n",
                                 cmd, optarg);
               return LVM_EINVALID_CMD_LINE;
            }
            break;

         DEBUG_HANDLE_CASE_D;

         case 'h':
         case '?':
            printf ( "\n%s  (IOP %d)\n\n%s -- Volume Group Merge\n\n"
                     "Synopsis:\n"
                     "---------\n\n"
                     "%s\n"
                     "\t[-A/--autobackup y/n]\n"
                     DEBUG_HELP
                     "\t[-h/--help]\n"
                     "\t[-l/--list]\n"
                     "\t[-t/--test]\n"
                     "\t[-v/--verbose]\n"
                     "\tDestinationVolumeGroupName SourceVolumeGroupName\n\n",
                     lvm_version, LVM_LIB_IOP_VERSION,  cmd, cmd);
            return 0;
            break;

         case 'l':
            if ( opt_l > 0) {
               fprintf ( stderr, "%s -- l option already given\n\n", cmd);
               return LVM_EINVALID_CMD_LINE;
            }
            opt_l++;
            break;

         case 't':
            if ( opt_t > 0) {
               fprintf ( stderr, "%s -- t option already given\n\n", cmd);
               return LVM_EINVALID_CMD_LINE;
            }
            opt_t++;
            break;

         case 'v':
            if ( opt_v > 0) {
               fprintf ( stderr, "%s -- v option already given\n\n", cmd);
               return LVM_EINVALID_CMD_LINE;
            }
            opt_v++;
            break;

         default:
            fprintf ( stderr, "%s -- invalid command line option \"%c\"\n\n",
                      cmd, c);
            return LVM_EINVALID_CMD_LINE;
      }
   }
  
   CMD_MINUS_CHK;
   LVM_CHECK_IOP;
   LVM_LOCK ( 0);
   CMD_CHECK_OPT_A_SET;


   if ( optind != argc - 2) {
      fprintf ( stderr, "%s -- please enter 2 volume group names\n\n", cmd);
      return LVM_EVGMERGE_VG_NAMES;
   }

   for ( v = optind; v < argc; v++) {
      if ( opt_v > 0) printf ( "%s -- checking volume group name \"%s\"\n",
                               cmd, argv[v]);
      if ( vg_check_name ( argv[v]) < 0) {
         fprintf ( stderr, "%s -- ERROR: invalid volume group name \"%s\"\n\n",
                           cmd, argv[v]);
         return LVM_EINVALID_CMD_LINE;
      }
   }

   vg_name_to = argv[optind++];
   vg_name_from = argv[optind];

   if ( opt_v > 0) printf ( "%s -- checking for volume group \"%s\" activity\n",
                            cmd, vg_name_from);
   if ( vg_check_active ( vg_name_from) == TRUE) {
      fprintf ( stderr, "%s -- ERROR: volume group \"%s\" must be inactive\n\n",
                        cmd, vg_name_from);
      return LVM_EVGMERGE_VG_CHECK_ACTIVE;
   }

   if ( opt_v > 0) printf ( "%s -- reading data of volume group \"%s\" "
                            "from \"%s\"\n",
                            cmd, vg_name_to, LVMTAB);
   if ( ( ret = lvm_tab_vg_read_with_pv_and_lv ( vg_name_to, &vg_to)) != 0) {
      if ( ret != -LVM_EVG_CFGRESTORE_OPEN) {
         fprintf ( stderr, "%s -- ERROR \"%s\" couldn't get volume "
                           "group data of \"%s\"\n\n",
                           cmd, lvm_error ( ret), vg_name_to);
      } else fprintf ( stderr, "\n");
      return LVM_EVGMERGE_VG_READ_TO;
   }

   memcpy ( &vg_to_this, vg_to, sizeof ( vg_to_this));
   vg_to = &vg_to_this;

   if ( opt_v > 0) printf ( "%s -- reading data of volume group \"%s\"\n",
                            cmd, vg_name_from);
   if ( ( ret = lvm_tab_vg_read_with_pv_and_lv ( vg_name_from,
                                                 &vg_from)) < 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" couldn't get data of volume "
                        "group \"%s\"\n\n",
                        cmd, lvm_error ( ret), vg_name_from);
      return LVM_EVGMERGE_VG_READ_FROM;
   }

   memcpy ( &vg_from_this, vg_from, sizeof ( vg_from_this));
   vg_from = &vg_from_this;

   np = 0;
   while ( vg_to->pv[np] != NULL) np++;
   np_sav = np;


   if ( opt_v > 0) printf ( "%s -- merging VGDA of volume group \"%s\" "
                            "into that of \"%s\"\n",
                            cmd, vg_name_from, vg_name_to);
   if ( ( ret = vg_setup_for_merge ( vg_to, vg_from)) < 0) {
      if ( ret == -LVM_EVG_SETUP_FOR_MERGE_PE_SIZE) {
         fprintf ( stderr, "%s -- ERROR: physical extent sizes of volume "
                           "groups \"%s\" and \"%s\" differ\n\n",
                           cmd, vg_name_from, vg_name_to);
      } else if ( ret == -LVM_EVG_SETUP_FOR_MERGE_PV_MAX) {
         fprintf ( stderr, "%s -- ERROR: maximum physical volume count "
                           "exceeded for volume group \"%s\"\n\n",
                           cmd, vg_name_to);
      } else if ( ret == -LVM_EVG_SETUP_FOR_MERGE_LV_MAX) {
         fprintf ( stderr, "%s -- ERROR: maximum logical volume count "
                           "exceeded for volume group \"%s\"\n\n",
                           cmd, vg_name_to);
      } else {
         fprintf ( stderr, "%s -- ERROR \"%s\" merging volume group \"%s\" "
                           "into \"%s\"\n\n",
                           cmd, lvm_error ( ret), vg_name_from, vg_name_to);
      }
      return LVM_EVGMERGE_VG_SETUP;
   }

   if ( opt_l > 0) vg_show_with_pv_and_lv ( vg_to);

   lvm_dont_interrupt ( 0);

   if ( vg_check_active ( vg_name_to) == TRUE) {
      /* extend vg_to with new physical volumes */
      for ( ; vg_to->pv[np] != NULL; np++) {
         if ( opt_v > 0) printf ( "%s -- extending volume group \"%s\" by "
                                  "physical volume \"%s\" in kernel\n",
                                  cmd, vg_name_to, vg_to->pv[np]->pv_name);
         /* because lv_create() increments the PE counter in kernel land... */
         pe_allocated_sav = vg_to->pv[np]->pe_allocated;
         vg_to->pv[np]->pe_allocated = 0;
         if ( opt_t == 0 &&
              ( ret = vg_extend ( vg_name_to, vg_to->pv[np], vg_to)) < 0) {
            fprintf ( stderr, "%s -- ERROR \"%s\" extending volume group "
                              "\"%s\" by physical volume \"%s\" in kernel\n",
                              cmd, lvm_error ( ret),
                              vg_name_to, vg_to->pv[np]->pv_name);
            for ( p = np_sav; p < np; p++) {
               if ( opt_v > 0) printf ( "%s -- trying to reduce volume group "
                                        "\"%s\" by physical volume \"%s\"\n",
                                        cmd, vg_name_to, vg_to->pv[p]->pv_name);
               if ( vg_reduce ( vg_name_to, vg_to->pv[p], vg_to) < 0) {
                  fprintf ( stderr, "%s -- ERROR reducing volume group \"%s\" "
                                    "by physical volume \"%s\"\n",
                                    cmd, vg_name_to, vg_to->pv[p]->pv_name);
               }
            }
            return LVM_EVGMERGE_VG_EXTEND;
         }
         /* restore PE counter for vg_write_with_pv_and_lv() */
         vg_to->pv[np]->pe_allocated = pe_allocated_sav;
      }
   
      /* extend vg_to with new logical volumes */
      for ( l = 0; l < vg_to->lv_max; l++) {
         if ( vg_to->lv[l] != NULL) {
            if ( opt_t == 0 &&
                 ( ret = lv_create ( vg_to,
                                     vg_to->lv[l],
                                     vg_to->lv[l]->lv_name)) < 0) {
               if ( ret != -EEXIST) {
                  fprintf ( stderr, "%s -- ERROR \"%s\" creating logical "
                                    "volume %s in kernel\n",
                                    cmd, lvm_error ( ret),
                                    vg_to->lv[l]->lv_name);
               }
            }
         }
      }
   }

   /* store vg on disk(s) */
   if ( opt_v > 0) printf ( "%s -- storing volume group data of "
                            "%s on disk(s)\n", cmd, vg_name_to);
   if ( opt_t == 0 &&
        ( ret = vg_write_with_pv_and_lv ( vg_to)) < 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" storing data of volume group "
                        "\"%s\" on disk(s)\n\n",
                        cmd, lvm_error ( ret), vg_name_to);
      return LVM_EVGMERGE_VG_WRITE;
   }

   if ( opt_v > 0) printf ( "%s -- changing lvmtab\n", cmd);
   if ( opt_t == 0 &&
        vg_cfgbackup ( vg_name_to, LVMTAB_DIR, opt_v, vg_to) == 0 &&
        opt_A > 0) {
      printf ( "%s -- doing automatic backup of volume group \"%s\"\n",
               cmd, vg_name_to);
      vg_cfgbackup ( vg_name_to, VG_BACKUP_DIR, opt_v, vg_to);
   } else {
      printf ( "%s -- WARNING: you don't have an automatic backup of \"%s\"\n",
               cmd, vg_name_to);
   }

   if ( opt_v > 0) printf ( "%s -- removing special files of volume "
                            "group \"%s\"\n", cmd, vg_name_from);
   if ( opt_t == 0) {
      if ( vg_remove_dir_and_group_and_nodes ( vg_name_from) < 0) {
         fprintf ( stderr, "%s -- ERROR removing special files of volume "
                           "group \"%s\"\n",
                           cmd, vg_name_from);
      }
   }

   if ( opt_v > 0) printf ( "%s -- removing special files for volume "
                            "group \"%s\"\n", cmd, vg_name_from);
   if ( opt_t == 0) {
      if ( vg_remove_dir_and_group_and_nodes ( vg_name_to) < 0) {
         fprintf ( stderr, "%s -- ERROR removing special files of volume "
                           "group \"%s\"\n",
                           cmd, vg_name_to);
      }
   }

   if ( opt_v > 0) printf ( "%s -- creating directory and nodes of volume "
                            "group \"%s\"\n",
                            cmd, vg_name_to);
   if ( opt_t == 0 &&
        ( ret = vg_create_dir_and_group_and_nodes ( vg_to, opt_v)) < 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" creating volume group "
                        "nodes of \"%s\"\n\n",
                        cmd, lvm_error ( ret), vg_name_to);
      return LVM_EVGMERGE_VG_CREATE_DIR_AND_GROUP_NODES;
   }

   if ( opt_v > 0) printf ( "%s -- removing \"%s\" entry of volume "
                            "group \"%s\"\n",
                            cmd, LVMTAB, vg_name_from);
   if ( opt_t == 0 &&
        ( ret = lvm_tab_vg_remove ( vg_name_from)) < 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" removing volume group \"%s\" entry "
                        "from \"%s\"\n",
                        cmd, lvm_error ( ret), vg_name_from, LVMTAB);
      return LVM_EVGMERGE_VG_REMOVE;
   }

   printf ( "%s -- volume group \"%s\" successfully merged into \"%s\"\n",
             cmd, vg_name_from, vg_name_to);
   if ( opt_t > 0) printf ( "%s -- this only has been a test run\n", cmd);

   lvm_interrupt ();
   LVM_UNLOCK ( 0);

   printf ( "\n");

   return 0;
}
