/*
 * tools/lvreduce.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * April 1997
 * April-June,September 1998
 * February,July,August,October 1999
 * February,November 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
 *
 *    16/10/1997 - change lv_get_index to lv_get_index_by_name
 *    11/09/1097 - added lvmtab handling
 *    30/04/1998 - changed to lv_status_byname()
 *    16/05/1998 - added lvmtab checking
 *    12/06/1998 - enhanced checking numbers in option arguments
 *    27/06/1998 - changed lvm_tab_* calling convention
 *    29/06/1998 - corrected size error message
 *    04/09/1998 - corrected some messages
 *    06/02/1999 - fixed lvm_check_number() usage
 *    06/07/1999 - avoided vg_status()
 *    15/08/1999 - enhanced to avoid reduction of snapshot logical volumes
 *    06/10/1999 - implemented support for long options
 *    15/02/2000 - use lvm_error()
 *    07/11/2000 - used LVM_VG_NAME environment variable
 *    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 c1 = 0;
   int l = 0;
   int opt_A = 1;
   int opt_A_set = 0;
   int opt_f = 0;
   int opt_l = 0;
   int opt_L = 0;
   int opt_v = 0;
   int ret = 0;
   int sign = 0;
   int size_rest = 0;
   long new_size = 0;
   char buffer[NAME_LEN];
   char *dummy = NULL;
#ifdef DEBUG
   char *options = "A:dfh?l:L:yv";
#else
   char *options = "A:fh?l:L:yv";
#endif
   struct option long_options[] = {
      { "autobackup", required_argument, NULL, 'A'},
#ifdef DEBUG
      { "debug",      no_argument,       NULL, 'd'},
#endif
      { "force",      no_argument,       NULL, 'f'},
      { "help",       no_argument,       NULL, 'h'},
      { "extents",    required_argument, NULL, 'l'},
      { "size",       required_argument, NULL, 'L'},
      { "yes",        no_argument,       NULL, 'v'},
      { "verbose",    no_argument,       NULL, 'v'},
      { NULL,         0,                 NULL, 0}
   };
   char *lv_name = NULL;
   char *vg_name = NULL;
   vg_t *vg = NULL;
   lv_t *lv = NULL;

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

   SUSER_CHECK;
   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;

#ifdef DEBUG
         case 'd':
            if ( opt_d > 0) {
               fprintf ( stderr, "%s -- d option already given\n\n", cmd);
               return LVM_EINVALID_CMD_LINE;
            }
            opt_d++;
            break;
#endif

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

         case 'h':
         case '?':
            printf ( "\n%s (IOP %d)\n\n%s -- Logical Volume Reduce\n\n"
                     "Synopsis:\n"
                     "---------\n\n"
                     "%s\n"
                     "\t[-A/--autobackup y/n]\n"
#ifdef DEBUG
                     "\t[-d/--debug]\n"
#endif
                     "\t[-f/--force]\n"
                     "\t[-h/-?/--help]\n"
                     "\t{-l/--extents [-]LogicalExtentsNumber |\n"
                     "\t -L/--size [-]LogicalVolumeSize[kKmMgGtT]}\n"
                     "\t[-v/--verbose]\n"
                     "\tLogicalVolume[Path]\n\n",
                     lvm_version, LVM_LIB_IOP_VERSION,  cmd, cmd);
            return 0;
            break;

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

            sign = 0;
            if ( *optarg == '-') { sign = -1; optarg++;}
            if ( ( new_size = lvm_check_number ( optarg, FALSE)) > 0) {
               opt_l++;
            } else {
               fprintf ( stderr, "%s -- ERROR option l argument \"%s\"\n\n",
                                 cmd, optarg);
               return LVM_EINVALID_CMD_LINE;
            }
            break;

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

            sign = 0;
            if ( *optarg == '-') { sign = -1; optarg++;}
            if ( ( new_size = lvm_check_number ( optarg, TRUE)) > 0) {
               opt_L++;
            } else {
               fprintf ( stderr, "%s -- ERROR option L argument \"%s\"\n\n",
                                 cmd, optarg);
               return LVM_EINVALID_CMD_LINE;
            }
            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",
                      cmd, c);
            return LVM_EINVALID_CMD_LINE;
      }
   }

   CMD_MINUS_CHK
   CMD_CHECK_OPT_A_SET;

   if ( optind == argc) {
      fprintf ( stderr, "%s -- please enter a logical volume name\n\n", cmd);
      return LVM_ELVREDUCE_LV_MISSING;
   }
   lv_name = argv[optind];
   LVM_CHECK_DEFAULT_VG_NAME ( lv_name, buffer, sizeof ( buffer));

   if ( lv_check_name ( lv_name) < 0) {
      fprintf ( stderr, "%s -- no valid logical volume name \"%s\"\n\n",
                cmd, lv_name);
      return LVM_ELVREDUCE_LV_NAME;
   }

   LVM_CHECK_IOP;
   LVM_LOCK ( 0);

   /* does LV exist? */
   if ( opt_v > 0) printf ( "%s -- checking existence of "
                            "logical volume \"%s\"\n",
                            cmd, lv_name);
   if ( lvm_tab_lv_check_exist ( lv_name) != TRUE) {
      fprintf ( stderr, "%s -- logical volume \"%s\" doesn't exist\n\n",
                cmd, lv_name);
      return LVM_ELVREDUCE_LV_CHECK_EXIST;
   }

   vg_name = vg_name_of_lv ( lv_name);

   if ( opt_v > 0) printf ( "%s -- checking for active logical volume \"%s\"\n",
                            cmd, lv_name);
   if ( lv_check_active ( vg_name, lv_name) != TRUE) {
      fprintf ( stderr, "%s -- logical volume \"%s\" isn't active\n\n",
                cmd, lv_name);
      return LVM_ELVREDUCE_LV_CHECK_ACTIVE;
   }

   if ( opt_v > 0) printf ( "%s -- reading data of volume group \"%s\" "
                            "from disk(s)\n",
                            cmd, vg_name);
   if ( ( ret = lvm_tab_vg_read_with_pv_and_lv ( vg_name, &vg)) != 0) {
      fprintf ( stderr, "%s -- can't reduce logical volume:"
                        " couldn't read volume group data of \"%s\"\n\n",
                        cmd, vg_name);
      return LVM_ELVREDUCE_VG_READ;
   }

   if ( opt_v > 0) printf ( "%s -- getting index of logical volume \"%s\" "
                            "in volume group \"%s\"\n",
                            cmd, lv_name, vg_name);
   if ( ( l = lv_get_index_by_name ( vg, lv_name)) < 0) {
      fprintf ( stderr, "%s -- ERROR: can't reduce logical volume \"%s\" "
                        "without getting it's index\n\n", cmd, lv_name);
      return LVM_ELVREDUCE_LV_GET_INDEX;
   }

   if ( opt_v > 0) printf ( "%s -- getting status of logical volume \"%s\" "
                            "from kernel\n",
                            cmd, lv_name);

   if ( ( ret = lv_status_byname ( vg_name, lv_name, &lv)) < 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" getting status of logical "
                        "volume \"%s\"\n\n",
                        cmd, lvm_error ( ret), lv_name);
      return LVM_ELVREDUCE_LV_STATUS_BYNAME;
   }

   if ( opt_L > 0 || opt_l > 0) {
      if ( opt_L > 0) new_size *= 2;
      else            new_size *= vg->pe_size;
      if ( new_size % vg->pe_size > 0) {
         new_size += vg->pe_size;
         printf ( "%s -- rounding size to physical extent boundary\n", cmd);
      }
      new_size = new_size / vg->pe_size * vg->pe_size;
      if ( new_size >= vg->lv[l]->lv_size) {
         fprintf ( stderr, "%s -- new size is not smaller than old one\n\n",
                   cmd);
         return LVM_ELVREDUCE_LV_SIZE;
      }
      if ( sign != 0) new_size = vg->lv[l]->lv_size - new_size;
      size_rest = new_size %
                  ( vg->lv[l]->lv_stripes * vg->pe_size);
      if ( size_rest != 0) {
         printf ( "%s -- rounding size %ld KB to stripe boundary size ",
                  cmd, new_size / 2);
         new_size = new_size - size_rest;
         printf ( "%ld KB\n", new_size / 2);
      }
   } else {
      fprintf ( stderr, "%s -- please give an l or L option\n\n", cmd);
      return LVM_EINVALID_CMD_LINE;
   }

   if ( new_size <= lv->lv_remap_ptr * lv->lv_chunk_size) {
      fprintf ( stderr, "%s -- size of snapshot would be too small\n", cmd);
      return LVM_EINVALID_CMD_LINE;
   }

   if ( lv->lv_status == LV_ACTIVE &&
        !(lv->lv_access & LV_SNAPSHOT)) {
      printf ( "%s -- WARNING: reducing active", cmd);
      if ( lv->lv_open > 0) printf ( " and open");
      printf ( " logical volume to %s\n"
               "%s -- THIS MAY DESTROY YOUR DATA (filesystem etc.)\n",
               ( dummy = lvm_show_size ( new_size / 2, SHORT)), cmd);
      free ( dummy); dummy = NULL;
   }

   if ( opt_v > 0) printf ( "%s -- setting up logical volume \"%s\" "
                            "for reduce\n",
                            cmd, lv_name);
   if ( ( ret = lv_setup_for_reduce ( vg_name, vg, lv_name, new_size)) != 0) {
      fprintf ( stderr, "%s -- ERROR setting logical volume \"%s\" up "
                        "for reduce\n\n",
                        cmd, lv_name);
      return LVM_ELVREDUCE_LV_SETUP;
   }

   if ( lv->lv_access & LV_SNAPSHOT) {
      if ( ( ret = lv_setup_COW_table_for_create (
                      vg,
                      vg->lv[lv_get_index_by_minor ( vg, vg->lv[l]->lv_snapshot_minor)]->lv_name,
                      l,
                      lv->lv_chunk_size * SECTOR_SIZE / 1024)) < 0) {
         fprintf ( stderr, "%s -- ERROR \"%s\" setting up snapshot "
                           "copy on write exception table for \"%s\"\n\n",
                           cmd, lvm_error ( ret), lv_name);
         return LVM_ELVEXTEND_LV_SETUP_COW_TABLE_FOR_CREATE;
      }
   }

   if ( opt_f == 0 &&
        !(lv->lv_access & LV_SNAPSHOT)) {
      c = 0;
      while ( c != 'n' && c != 'y') {
         if ( c == '\n' || c == 0)
            printf ( "%s -- do you really want to reduce \"%s\"? [y/n]: ",
                     cmd, lv_name);
         c = tolower ( getchar ());
      }
      c1 = c;
      while ( c != '\n') c = tolower ( getchar ());
      if ( c1 == 'n') {
         printf ( "%s -- logical volume \"%s\" not reduced\n\n", cmd, lv_name);
         return 0;
      }
   }

   lvm_dont_interrupt ( 0);


   /* create it in kernel */
   if ( opt_v > 0) printf ( "%s -- creating reduced logical volume "
                            "VGDA in kernel\n", cmd);
   if ( ( ret = lv_reduce ( vg, vg->lv[l], lv_name)) != 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" reducing logical volume \"%s\" "
                        "in kernel\n\n", 
                        cmd, lvm_error ( ret), lv_name);
      return LVM_ELVREDUCE_LV_REDUCE;
   }

   if ( opt_v > 0) printf ( "%s -- storing reduced logical volume "
                            "data on disk(s)\n", cmd);
   if ( ( ret = vg_write_with_pv_and_lv ( vg)) != 0) {
      fprintf ( stderr, "%s -- ERROR \"%s\" storing data of volume "
                        "group \"%s\" on disks\n\n", 
                        cmd, lvm_error ( ret), vg_name);
      return LVM_ELVREDUCE_VG_WRITE;
   }


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

   printf ( "%s -- logical volume \"%s\" successfully reduced\n\n",
             cmd, lv_name);

   return 0;
}
