folder.c 20.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2002, 2003, 
   2005 Free Software Foundation, Inc.

   GNU Mailutils 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.

   GNU Mailutils 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 GNU Mailutils; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301 USA */

/* MH folder command */

#include <mh.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

#include <dirent.h>

#define obstack_chunk_alloc malloc
#define obstack_chunk_free free
#include <obstack.h>

const char *program_version = "folder (" PACKAGE_STRING ")";
/* TRANSLATORS: Please, preserve the vertical tabulation (^K character)
   in this message */
static char doc[] = N_("GNU MH folder\v\
Use -help to obtain the list of traditional MH options.");
static char args_doc[] = N_("[action] [msg]");

static struct argp_option options[] = {
  {N_("Actions are:"), 0, 0, OPTION_DOC, NULL, 0 },
  {"print", ARG_PRINT, NULL, 0,
   N_("List the folders (default)"), 1 },
  {"list",  ARG_LIST,  NULL, 0,
   N_("List the contents of the folder stack"), 1},
  {"pack",  ARG_PACK,  N_("NUMBER"), OPTION_ARG_OPTIONAL,
   N_("Remove holes in message numbering. Begin numbering from NUMBER (default: first message number)"), 1},
  {"push",  ARG_PUSH,  N_("FOLDER"), OPTION_ARG_OPTIONAL,
    N_("Push the folder on the folder stack. If FOLDER is specified, it is pushed. "
       "Otherwise, if a folder is given in the command line (via + or --folder), "
       "it is pushed on stack. Otherwise, the current folder and the top of the folder "
       "stack are exchanged"), 1},
  {"pop",   ARG_POP,    NULL, 0,
   N_("Pop the folder off the folder stack"), 1},
  
  {N_("Options are:"), 0, 0, OPTION_DOC, NULL, 2 },
  
  {"folder", ARG_FOLDER, N_("FOLDER"), 0,
   N_("Specify folder to operate upon"), 3},
  {"all",    ARG_ALL,    NULL, 0,
   N_("List all folders"), 3},
  {"create", ARG_CREATE, N_("BOOL"), OPTION_ARG_OPTIONAL, 
    N_("Create non-existing folders"), 3},
  {"nocreate", ARG_NOCREATE, NULL, OPTION_HIDDEN, ""},
  {"fast",   ARG_FAST, N_("BOOL"), OPTION_ARG_OPTIONAL, 
    N_("List only the folder names"), 3},
  {"nofast", ARG_NOFAST, NULL, OPTION_HIDDEN, ""},
  {"header", ARG_HEADER, N_("BOOL"), OPTION_ARG_OPTIONAL, 
    N_("Print the header line"), 3},
  {"noheader", ARG_NOHEADER, NULL, OPTION_HIDDEN, ""},
  {"recurse",ARG_RECURSIVE, N_("BOOL"), OPTION_ARG_OPTIONAL,
    N_("Scan folders recursively"), 3},
  {"norecurse", ARG_NORECURSIVE, NULL, OPTION_HIDDEN, ""},
  {"total",  ARG_TOTAL, N_("BOOL"), OPTION_ARG_OPTIONAL, 
    N_("Output the total statistics"), 3},
  {"nototal", ARG_NOTOTAL, NULL, OPTION_HIDDEN, ""},
  {"verbose", ARG_VERBOSE, NULL, 0,
   N_("Verbosely list actions taken"), 3},
  {"dry-run", ARG_DRY_RUN, NULL, 0,
   N_("Do nothing, print what would be done (with --pack)"), 3},
   
  {"license", ARG_LICENSE, 0,      0,
   N_("Display software license"), -1},

  {NULL},
};

/* Traditional MH options */
struct mh_option mh_option[] = {
  {"print",   2, 0, NULL },
  {"list",    1, 0, NULL },
  {"push",    2, 0, NULL },
  {"pop",     2, 0, NULL },
  {"all",     1, 0, NULL },
  {"pack",    2, 0, NULL },
  {"create",  1, MH_OPT_BOOL, NULL},
  {"fast",    1, MH_OPT_BOOL, NULL},
  {"header",  1, MH_OPT_BOOL, NULL},
  {"recurse", 1, MH_OPT_BOOL, NULL},
  {"total",   1, MH_OPT_BOOL, NULL},
  {NULL},
};

typedef int (*folder_action) ();

static int action_print ();
static int action_list ();
static int action_push ();
static int action_pop ();
static int action_pack ();
static folder_action action = action_print;

int show_all = 0; /* List all folders. Raised by --all switch */
int create_flag = -1; /* Create non-existent folders (--create).
		         -1: Prompt before creating
		          0: Do not create
		          1: Always create without prompting */
int fast_mode = 0; /* Fast operation mode. (--fast) */
int print_header = 0; /* Display the header line (--header) */
int recurse = 0;   /* Recurse sub-folders */
int print_total;   /* Display total stats */
int verbose = 0;   /* Verbosely list actions taken */
size_t pack_start; /* Number to be assigned to the first message in packed
		      folder. 0 means do not change first message number. */
int dry_run;       /* Dry run mode */ 
char *push_folder; /* Folder name to push on stack */

char *mh_seq_name; /* Name of the mh sequence file (defaults to
		      .mh_sequences) */

static int
opt_handler (int key, char *arg, void *unused, struct argp_state *state)
{
  switch (key)
    {
    case ARG_DRY_RUN:
      dry_run++;
      break;
	
    case ARG_PACK:
      action = action_pack;
      if (arg)
	{
	  char *p;
	  pack_start = strtoul (arg, &p, 10);
	  if (*p)
	    argp_error (state, _("Invalid number"));
	}
      break;
      
    case ARG_PRINT:
      action = action_print;
      break;
      
    case ARG_LIST:
      action = action_list;
      break;

    case ARG_PUSH:
      action = action_push;
      if (arg)
	{
	  push_folder = mh_current_folder ();
	  current_folder = arg;
	}
      break;
      
    case ARG_POP:
      action = action_pop;
      break;
      
    case ARG_ALL:
      show_all++;
      break;

    case ARG_CREATE:
      create_flag = is_true (arg);
      break;

    case ARG_NOCREATE:
      create_flag = 0;
      
    case ARG_FAST:
      fast_mode = is_true (arg);
      break;

    case ARG_NOFAST:
      fast_mode = 0;
      break;
      
    case ARG_HEADER:
      print_header = is_true (arg);
      break;

    case ARG_NOHEADER:
      print_header = 0;
      break;
      
    case ARG_RECURSIVE:
      recurse = is_true (arg);
      break;

    case ARG_NORECURSIVE:
      recurse = 0;
      break;
      
    case ARG_TOTAL:
      print_total = is_true (arg);
      break;

    case ARG_NOTOTAL:
      print_total = 0;
      break;
      
    case ARG_FOLDER:
      push_folder = mh_current_folder ();
      current_folder = arg;
      break;
      
    case ARG_LICENSE:
      mh_license (argp_program_version);
      break;

    case ARG_VERBOSE:
      verbose++;
      break;
      
    default:
      return 1;
    }
  return 0;
}


/* ************************************************************* */
/* Printing */

struct folder_info
{
  char *name;              /* Folder name */
  size_t message_count;    /* Number of messages in this folder */
  size_t min;              /* First used sequence number (=uid) */
  size_t max;              /* Last used sequence number */
  size_t cur;              /* UID of the current message */
  size_t others;           /* Number of non-message files */ 
};

struct obstack folder_info_stack; /* Memory storage for folder infp */
struct folder_info *folder_info;  /* Finalized array of information
				     structures */
size_t folder_info_count;         /* Number of the entries in the array */

size_t message_count;             /* Total number of messages */

int name_prefix_len;              /* Length of the mu_path_folder_dir */

void
install_folder_info (const char *name, struct folder_info *info)
{
  info->name = strdup (name) + name_prefix_len;
  obstack_grow (&folder_info_stack, info, sizeof (*info));
  folder_info_count++;
  message_count += info->message_count;
}

static int
folder_info_comp (const void *a, const void *b)
{
  return strcmp (((struct folder_info *)a)->name,
		 ((struct folder_info *)b)->name);
}

static void
read_seq_file (struct folder_info *info, const char *prefix, const char *name)
{
  char *pname = NULL;
  mh_context_t *ctx;
  char *p;
  
  asprintf (&pname, "%s/%s", prefix, name);
  if (!pname)
    abort ();
  ctx = mh_context_create (pname, 1);
  mh_context_read (ctx);
  
  p = mh_context_get_value (ctx, "cur", NULL);
  if (p)
    info->cur = strtoul (p, NULL, 0);
  free (pname);
  free (ctx);
}

static void
_scan (const char *name, int depth)
{
  DIR *dir;
  struct dirent *entry;
  struct folder_info info;
  char *p;
  struct stat st;
  size_t uid;

  dir = opendir (name);

  if (!dir && errno == ENOENT)
    {
      if (create_flag)
	{
	  if (mh_check_folder (name, create_flag == -1))
	    {
	      push_folder = 0;
	      return;
	    }
	  dir = opendir (name);
	}
      else
	exit (1);
    }

  if (!dir)
    {
      mh_error (_("Cannot scan folder %s: %s"), name, strerror (errno));
      return;
    }

  if (!recurse)
    {
      closedir (dir);
      if (fast_mode && depth > 0)
	{
	  memset (&info, 0, sizeof (info));
	  info.name = strdup (name);
	  install_folder_info (name, &info);
	  return;
	}
      
      if (depth > 1)
	return;
    }
  
  memset (&info, 0, sizeof (info));
  info.name = strdup (name);
  while ((entry = readdir (dir)))
    {
      if (entry->d_name[0] == '.')
	{
	  if (strcmp (entry->d_name, mh_seq_name) == 0)
	    read_seq_file (&info, name, entry->d_name);
	}
      else if (entry->d_name[0] != ',')
	{
	  asprintf (&p, "%s/%s", name, entry->d_name);
	  if (stat (p, &st) < 0)
	    mh_error (_("Cannot stat %s: %s"), p, strerror (errno));
	  else if (S_ISDIR (st.st_mode))
	    {
	      info.others++;
	      _scan (p, depth+1);
	    }
	  else
	    {
	      char *endp;
	      uid = strtoul (entry->d_name, &endp, 10);
	      if (*endp)
		info.others++;
	      else
		{
		  info.message_count++;
		  if (info.min == 0 || uid < info.min)
		    info.min = uid;
		  if (uid > info.max)
		    info.max = uid;
		}
	    }
	}
    }
  
  if (info.cur)
    {
      asprintf (&p, "%s/%s", name, mu_umaxtostr (0, info.cur));
      if (stat (p, &st) < 0 || !S_ISREG (st.st_mode))
	info.cur = 0;
      free (p);
    }
  closedir (dir);
  if (depth > 0)
    install_folder_info (name, &info);
}
    
static void
print_all ()
{
  struct folder_info *info, *end = folder_info + folder_info_count;

  for (info = folder_info; info < end; info++)
    {
      int len = strlen (info->name);
      if (len < 22)
	printf ("%22.22s", info->name);
      else
	printf ("%s", info->name);
      
      if (strcmp (info->name, current_folder) == 0)
	printf ("+");
      else
	printf (" ");
      
      if (info->message_count)
	{
	  printf (ngettext(" has %4lu message  (%4lu-%4lu)",
			   " has %4lu messages (%4lu-%4lu)",
			   info->message_count),
		  (unsigned long) info->message_count,
		  (unsigned long) info->min,
		  (unsigned long) info->max);
	  if (info->cur)
	    printf ("; cur=%4lu", (unsigned long) info->cur);
	}
      else
	{
	  printf (_(" has no messages"));
	}
      
      if (info->others)
	{
	  if (!info->cur)
	    printf (";           ");
	  else
	    printf ("; ");
	  printf (_("(others)"));
	}
      printf (".\n");
    }
}

static void
print_fast ()
{
  struct folder_info *info, *end = folder_info + folder_info_count;

  for (info = folder_info; info < end; info++)
    printf ("%s\n", info->name);
}

static int
action_print ()
{
  const char *folder_dir = mu_folder_directory ();
  mh_seq_name = mh_global_profile_get ("mh-sequences", MH_SEQUENCES_FILE);

  name_prefix_len = strlen (folder_dir);
  if (folder_dir[name_prefix_len - 1] == '/')
    name_prefix_len++;
  name_prefix_len++;  /* skip past the slash */

  obstack_init (&folder_info_stack);

  if (show_all)
    {
      _scan (folder_dir, 0);
    }
  else
    {
      char *p = mh_expand_name (NULL, current_folder, 0);
      _scan (p, 1);
      free (p);
    }
  
  folder_info = obstack_finish (&folder_info_stack);
  qsort (folder_info, folder_info_count, sizeof (folder_info[0]),
	 folder_info_comp);

  if (fast_mode)
    print_fast ();
  else
    {
      if (print_header)                                   
	printf (_("Folder                  # of messages     (  range  )  cur msg   (other files)\n"));
		
      print_all ();

      if (print_total)
	{
	  printf ("\n%24.24s=", _("TOTAL"));
	  printf (ngettext ("%4lu message  ", "%4lu messages ",
			    message_count),
		  (unsigned long) message_count);
	  printf (ngettext ("in %4lu folder", "in %4lu folders",
			    folder_info_count),
		  (unsigned long) folder_info_count);
	  printf ("\n");
	}
    }
  if (push_folder)
    mh_global_save_state ();

  return 0;
}


/* ************************************************************* */
/* Listing */

static int
action_list ()
{
  char *stack = mh_global_context_get ("Folder-Stack", NULL);

  printf ("%s", current_folder);
  if (stack)
    printf (" %s", stack);
  printf ("\n");
  return 0;
}


/* ************************************************************* */
/* Push & pop */

static char *
make_stack (char *folder, char *old_stack)
{
  char *stack = NULL;
  if (old_stack)
    asprintf (&stack,  "%s %s", folder, old_stack);
  else
    stack = strdup (folder);
  return stack;
}

static int
action_push ()
{
  char *stack = mh_global_context_get ("Folder-Stack", NULL);
  char *new_stack = NULL;

  if (push_folder)
    new_stack = make_stack (push_folder, stack);
  else
    {
      char *s, *p = strtok_r (stack, " ", &s);
      new_stack = make_stack (current_folder, stack);
      current_folder = p;
    }
  
  mh_global_context_set ("Folder-Stack", new_stack);
  action_list ();
  mh_global_save_state ();
  return 0;
}

static int
action_pop ()
{
  char *stack = mh_global_context_get ("Folder-Stack", NULL);
  char *s, *p;

  if (stack)
    {
      p = strtok_r (stack, " ", &s);
      if (s[0] == 0)
	s = NULL;
    }
  else
    {
      p = current_folder;
      s = NULL;
    }
  mh_global_context_set ("Folder-Stack", s);
  current_folder = p;
  action_list ();
  mh_global_save_state ();
  return 0;
}


/* ************************************************************* */
/* Packing */

struct pack_tab
{
  size_t orig;
  size_t new;
};

static int
pack_rename (struct pack_tab *tab, int reverse)
{
  int rc;
  const char *s1;
  const char *s2;
  const char *from, *to;
  
  s1 = mu_umaxtostr (0, tab->orig);
  s2 = mu_umaxtostr (1, tab->new);

  if (!reverse)
    {
      from = s1;
      to = s2;
    }
  else
    {
      from = s2;
      to = s1;
    }

  if (verbose)
    fprintf (stderr, _("Renaming %s to %s\n"), from, to);

  if (!dry_run)
    {
      if ((rc = rename (from, to)))
	mh_error (_("cannot rename `%s' to `%s': %s"),
		  from, to, mu_strerror (errno));
    }
  else
    rc = 0;
  
  return rc;
}

/* Reverse ordering of COUNT entries in array TAB */
static void
reverse (struct pack_tab *tab, size_t count)
{
  size_t i, j;

  for (i = 0, j = count-1; i < j; i++, j--)
    {
      size_t tmp;
      tmp = tab[i].orig;
      tab[i].orig = tab[j].orig;
      tab[j].orig = tmp;

      tmp = tab[i].new;
      tab[i].new = tab[j].new;
      tab[j].new = tmp;
    }
} 

static void
roll_back (const char *folder_name, struct pack_tab *pack_tab, size_t i)
{
  size_t start;
  
  if (i == 0)
    return;
  
  start = i - 1;
  mh_error (_("Rolling back changes..."));
  while (--i >= 0)
    if (pack_rename (pack_tab + i, 1))
      {
	mh_error (_("CRITICAL ERROR: Folder `%s' left in an inconsistent state, because an error\n"
		    "occurred while trying to roll back the changes.\n"
		    "Message range %s-%s has been renamed to %s-%s."),
		  folder_name,
		  mu_umaxtostr (0, pack_tab[0].orig),
                  mu_umaxtostr (1, pack_tab[start].orig),
		  mu_umaxtostr (2, pack_tab[0].new),
                  mu_umaxtostr (3, pack_tab[start].new));
	mh_error (_("You will have to fix it manually."));
	exit (1);
      }
  mh_error (_("Folder `%s' restored successfully"), folder_name);
}

struct fixup_data
{
  const char *folder_dir;
  struct pack_tab *pack_tab;
  size_t count;
};

static int
pack_cmp (const void *a, const void *b)
{
  const struct pack_tab *pa = a;
  const struct pack_tab *pb = b;

  if (pa->orig < pb->orig)
    return -1;
  else if (pa->orig > pb->orig)
    return 1;
  return 0;
}

static size_t
pack_xlate (struct pack_tab *pack_tab, size_t count, size_t n)
{
  struct pack_tab key, *p;

  key.orig = n;
  p = bsearch (&key, pack_tab, count, sizeof pack_tab[0], pack_cmp);
  return p ? p->new : 0;
}

static int
_fixup (char *name, char *value, struct fixup_data *fd, int flags)
{
  int i, j, argc;
  char **argv;
  mh_msgset_t msgset;

  if (verbose)
    fprintf (stderr, "Sequence `%s'...\n", name);
  
  if (mu_argcv_get (value, "", NULL, &argc, &argv))
    return 0;

  msgset.list = xcalloc (argc, sizeof msgset.list[0]);
  for (i = j = 0; i < argc; i++)
    {
      size_t n = pack_xlate (fd->pack_tab, fd->count,
			     strtoul (argv[i], NULL, 0));
      if (n)
	msgset.list[j++] = n;
    }
  msgset.count = j;

  mh_seq_add (name, &msgset, flags | SEQ_ZERO);
  free (msgset.list);

  if (verbose)
    {
      char *p = mh_seq_read (name, flags);
      fprintf (stderr, "Sequence %s: %s\n", name, p);
    }
  
  return 0;
}

static int
fixup_global (char *name, char *value, void *data)
{
  return _fixup (name, value, data, 0);
}

static int
fixup_private (char *name, char *value, void *data)
{
  struct fixup_data *fd = data;
  int nlen = strlen (name);  
  if (nlen < 4 || memcmp (name, "atr-", 4))
    return 0;
  name += 4;

  nlen = strlen (name) - strlen (fd->folder_dir);
  if (nlen > 0 && strcmp (name + nlen, fd->folder_dir) == 0)
    {
      name[nlen-1] = 0;
      return _fixup (name, value, fd, SEQ_PRIVATE);
    }
  return 0;
}

int
action_pack ()
{
  const char *folder_dir = mh_expand_name (NULL, current_folder, 0);
  mu_mailbox_t mbox = mh_open_folder (current_folder, 0);
  struct pack_tab *pack_tab;
  size_t i, count, start;
  int status;
  struct fixup_data fd;
  
  /* Allocate pack table */
  if (mu_mailbox_messages_count (mbox, &count))
    {
      mh_error (_("Cannot read input mailbox: %s"), mu_strerror (errno));
      return 1;
    }
  pack_tab = xcalloc (count, sizeof pack_tab[0]); /* Never freed. No use to
						     try to. */

  /* Populate it with message numbers */
  if (verbose)
    fprintf (stderr, _("Getting message numbers.\n"));
    
  for (i = 0; i < count; i++)
    {
      mu_message_t msg;
      status = mu_mailbox_get_message (mbox, i + 1, &msg);
      if (status)
	{
	  mh_error (_("%d: cannot get message: %s"), i, mu_strerror (status));
	  return 1;
	}
      mh_message_number (msg, &pack_tab[i].orig);
    }
  if (verbose)
    fprintf (stderr, ngettext ("%s message number collected.\n",
			       "%s message numbers collected.\n",
			       (unsigned long) count),
	     mu_umaxtostr (0, count));
  
  mu_mailbox_close (mbox);
  mu_mailbox_destroy (&mbox);

  /* Compute new message numbers */
  if (pack_start == 0)
    pack_start = pack_tab[0].orig;

  for (i = 0, start = pack_start; i < count; i++)
    pack_tab[i].new = start++;

  if (pack_start > pack_tab[0].orig)
    {
      if (verbose)
	fprintf (stderr, _("Reverting pack table.\n"));
      reverse (pack_tab, i);
    }
  
  /* Change to the folder directory and rename messages */
  status = chdir (folder_dir);
  if (status)
    {
      mh_error (_("cannot change to directory `%s': %s"),
		folder_dir, mu_strerror (status));
      return 1;
    }

  for (i = 0; i < count; i++)
    {
      if (pack_rename (pack_tab + i, 0))
	{
	  roll_back (folder_dir, pack_tab, i);
	  return 1;
	}
    }

  if (verbose)
    fprintf (stderr, _("Finished packing messages.\n"));

  /* Fix-up sequences */
  fd.folder_dir = folder_dir;
  fd.pack_tab = pack_tab;
  fd.count = count;
  if (verbose)
    fprintf (stderr, _("Fixing global sequences\n"));
  mh_global_sequences_iterate (fixup_global, &fd);
  if (verbose)
    fprintf (stderr, _("Fixing private sequences\n"));
  mh_global_context_iterate (fixup_private, &fd);

  if (!dry_run)
    mh_global_save_state ();
  
  return 0;
}

int
main (int argc, char **argv)
{
  int index = 0;
  mh_msgset_t msgset;

  /* Native Language Support */
  mu_init_nls ();

  mu_argp_init (program_version, NULL);
  mh_argp_parse (&argc, &argv, 0, options, mh_option, args_doc, doc,
		 opt_handler, NULL, &index);

  /* If  folder  is invoked by a name ending with "s" (e.g.,  folders),
     `-all'  is  assumed */
  if (program_invocation_short_name[strlen (program_invocation_short_name) - 1] == 's')
    show_all++;

  if (argc - index == 1)
    {
      mu_mailbox_t mbox = mh_open_folder (current_folder, 0);
      mh_msgset_parse (mbox, &msgset, argc - index, argv + index, "cur");
      mh_msgset_current (mbox, &msgset, 0);
      mh_global_save_state ();
      mu_mailbox_close (mbox);
      mu_mailbox_destroy (&mbox);
    }
  else if (argc - index > 1)
    {
      mh_error (_("Too many arguments"));
      exit (1);
    }
  
  if (show_all)
    print_header = print_total = 1;
  
  return (*action) ();
}