]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
Remove code repetition in the doc ID bitmap code.
[notmuch] / notmuch-new.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22
23 #include <unistd.h>
24
25 typedef struct _filename_node {
26     char *filename;
27     struct _filename_node *next;
28 } _filename_node_t;
29
30 typedef struct _filename_list {
31     unsigned count;
32     _filename_node_t *head;
33     _filename_node_t **tail;
34 } _filename_list_t;
35
36 typedef struct {
37     int output_is_a_tty;
38     int verbose;
39     const char **new_tags;
40     size_t new_tags_length;
41
42     int total_files;
43     int processed_files;
44     int added_messages;
45     struct timeval tv_start;
46
47     _filename_list_t *removed_files;
48     _filename_list_t *removed_directories;
49
50     notmuch_bool_t synchronize_flags;
51     _filename_list_t *message_ids_to_sync;
52 } add_files_state_t;
53
54 static volatile sig_atomic_t do_print_progress = 0;
55
56 static void
57 handle_sigalrm (unused (int signal))
58 {
59     do_print_progress = 1;
60 }
61
62 static volatile sig_atomic_t interrupted;
63
64 static void
65 handle_sigint (unused (int sig))
66 {
67     ssize_t ignored;
68     static char msg[] = "Stopping...         \n";
69
70     ignored = write(2, msg, sizeof(msg)-1);
71     interrupted = 1;
72 }
73
74 static _filename_list_t *
75 _filename_list_create (const void *ctx)
76 {
77     _filename_list_t *list;
78
79     list = talloc (ctx, _filename_list_t);
80     if (list == NULL)
81         return NULL;
82
83     list->head = NULL;
84     list->tail = &list->head;
85     list->count = 0;
86
87     return list;
88 }
89
90 static void
91 _filename_list_add (_filename_list_t *list,
92                     const char *filename)
93 {
94     _filename_node_t *node = talloc (list, _filename_node_t);
95
96     list->count++;
97
98     node->filename = talloc_strdup (list, filename);
99     node->next = NULL;
100
101     *(list->tail) = node;
102     list->tail = &node->next;
103 }
104
105 static void
106 generic_print_progress (const char *action, const char *object,
107                         struct timeval tv_start, unsigned processed, unsigned total)
108 {
109     struct timeval tv_now;
110     double elapsed_overall, rate_overall;
111
112     gettimeofday (&tv_now, NULL);
113
114     elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
115     rate_overall = processed / elapsed_overall;
116
117     printf ("%s %d ", action, processed);
118
119     if (total) {
120         printf ("of %d %s", total, object);
121         if (processed > 0 && elapsed_overall > 0.5) {
122             double time_remaining = ((total - processed) / rate_overall);
123             printf (" (");
124             notmuch_time_print_formatted_seconds (time_remaining);
125             printf (" remaining)");
126         }
127     } else {
128         printf ("%s", object);
129         if (elapsed_overall > 0.5)
130             printf (" (%d %s/sec.)", (int) rate_overall, object);
131     }
132     printf (".\033[K\r");
133
134     fflush (stdout);
135 }
136
137 static int
138 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
139 {
140     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
141 }
142
143 static int
144 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
145 {
146     return strcmp ((*a)->d_name, (*b)->d_name);
147 }
148
149 /* Test if the directory looks like a Maildir directory.
150  *
151  * Search through the array of directory entries to see if we can find all
152  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
153  *
154  * Return 1 if the directory looks like a Maildir and 0 otherwise.
155  */
156 static int
157 _entries_resemble_maildir (struct dirent **entries, int count)
158 {
159     int i, found = 0;
160
161     for (i = 0; i < count; i++) {
162         if (entries[i]->d_type != DT_DIR && entries[i]->d_type != DT_UNKNOWN)
163             continue;
164
165         if (strcmp(entries[i]->d_name, "new") == 0 ||
166             strcmp(entries[i]->d_name, "cur") == 0 ||
167             strcmp(entries[i]->d_name, "tmp") == 0)
168         {
169             found++;
170             if (found == 3)
171                 return 1;
172         }
173     }
174
175     return 0;
176 }
177
178 /* Examine 'path' recursively as follows:
179  *
180  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
181  *   o Ask the database for its timestamp of 'path' (db_mtime)
182  *
183  *   o Ask the filesystem for files and directories within 'path'
184  *     (via scandir and stored in fs_entries)
185  *   o Ask the database for files and directories within 'path'
186  *     (db_files and db_subdirs)
187  *
188  *   o Pass 1: For each directory in fs_entries, recursively call into
189  *     this same function.
190  *
191  *   o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
192  *     simultaneously with db_files and db_subdirs. Look for one of
193  *     three interesting cases:
194  *
195  *         1. Regular file in fs_entries and not in db_files
196  *            This is a new file to add_message into the database.
197  *
198  *         2. Filename in db_files not in fs_entries.
199  *            This is a file that has been removed from the mail store.
200  *
201  *         3. Directory in db_subdirs not in fs_entries
202  *            This is a directory that has been removed from the mail store.
203  *
204  *     Note that the addition of a directory is not interesting here,
205  *     since that will have been taken care of in pass 1. Also, we
206  *     don't immediately act on file/directory removal since we must
207  *     ensure that in the case of a rename that the new filename is
208  *     added before the old filename is removed, (so that no
209  *     information is lost from the database).
210  *
211  *   o Tell the database to update its time of 'path' to 'fs_mtime'
212  */
213 static notmuch_status_t
214 add_files_recursive (notmuch_database_t *notmuch,
215                      const char *path,
216                      add_files_state_t *state)
217 {
218     DIR *dir = NULL;
219     struct dirent *entry = NULL;
220     char *next = NULL;
221     time_t fs_mtime, db_mtime;
222     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
223     notmuch_message_t *message = NULL;
224     struct dirent **fs_entries = NULL;
225     int i, num_fs_entries;
226     notmuch_directory_t *directory;
227     notmuch_filenames_t *db_files = NULL;
228     notmuch_filenames_t *db_subdirs = NULL;
229     struct stat st;
230     notmuch_bool_t is_maildir, new_directory;
231     const char **tag;
232
233     if (stat (path, &st)) {
234         fprintf (stderr, "Error reading directory %s: %s\n",
235                  path, strerror (errno));
236         return NOTMUCH_STATUS_FILE_ERROR;
237     }
238
239     /* This is not an error since we may have recursed based on a
240      * symlink to a regular file, not a directory, and we don't know
241      * that until this stat. */
242     if (! S_ISDIR (st.st_mode))
243         return NOTMUCH_STATUS_SUCCESS;
244
245     fs_mtime = st.st_mtime;
246
247     directory = notmuch_database_get_directory (notmuch, path);
248     db_mtime = notmuch_directory_get_mtime (directory);
249
250     if (db_mtime == 0) {
251         new_directory = TRUE;
252         db_files = NULL;
253         db_subdirs = NULL;
254     } else {
255         new_directory = FALSE;
256         db_files = notmuch_directory_get_child_files (directory);
257         db_subdirs = notmuch_directory_get_child_directories (directory);
258     }
259
260     /* If the database knows about this directory, then we sort based
261      * on strcmp to match the database sorting. Otherwise, we can do
262      * inode-based sorting for faster filesystem operation. */
263     num_fs_entries = scandir (path, &fs_entries, 0,
264                               new_directory ?
265                               dirent_sort_inode : dirent_sort_strcmp_name);
266
267     if (num_fs_entries == -1) {
268         fprintf (stderr, "Error opening directory %s: %s\n",
269                  path, strerror (errno));
270         ret = NOTMUCH_STATUS_FILE_ERROR;
271         goto DONE;
272     }
273
274     /* Pass 1: Recurse into all sub-directories. */
275     is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
276
277     for (i = 0; i < num_fs_entries; i++) {
278         if (interrupted)
279             break;
280
281         entry = fs_entries[i];
282
283         /* We only want to descend into directories.
284          * But symlinks can be to directories too, of course.
285          *
286          * And if the filesystem doesn't tell us the file type in the
287          * scandir results, then it might be a directory (and if not,
288          * then we'll stat and return immediately in the next level of
289          * recursion). */
290         if (entry->d_type != DT_DIR &&
291             entry->d_type != DT_LNK &&
292             entry->d_type != DT_UNKNOWN)
293         {
294             continue;
295         }
296
297         /* Ignore special directories to avoid infinite recursion.
298          * Also ignore the .notmuch directory and any "tmp" directory
299          * that appears within a maildir.
300          */
301         /* XXX: Eventually we'll want more sophistication to let the
302          * user specify files to be ignored. */
303         if (strcmp (entry->d_name, ".") == 0 ||
304             strcmp (entry->d_name, "..") == 0 ||
305             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
306             strcmp (entry->d_name, ".notmuch") ==0)
307         {
308             continue;
309         }
310
311         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
312         status = add_files_recursive (notmuch, next, state);
313         if (status && ret == NOTMUCH_STATUS_SUCCESS)
314             ret = status;
315         talloc_free (next);
316         next = NULL;
317     }
318
319     /* If the directory's modification time in the filesystem is the
320      * same as what we recorded in the database the last time we
321      * scanned it, then we can skip the second pass entirely.
322      *
323      * We test for strict equality here to avoid a bug that can happen
324      * if the system clock jumps backward, (preventing new mail from
325      * being discovered until the clock catches up and the directory
326      * is modified again).
327      */
328     if (fs_mtime == db_mtime)
329         goto DONE;
330
331     /* Pass 2: Scan for new files, removed files, and removed directories. */
332     for (i = 0; i < num_fs_entries; i++)
333     {
334         if (interrupted)
335             break;
336
337         entry = fs_entries[i];
338
339         /* Check if we've walked past any names in db_files or
340          * db_subdirs. If so, these have been deleted. */
341         while (notmuch_filenames_valid (db_files) &&
342                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
343         {
344             char *absolute = talloc_asprintf (state->removed_files,
345                                               "%s/%s", path,
346                                               notmuch_filenames_get (db_files));
347
348             _filename_list_add (state->removed_files, absolute);
349
350             notmuch_filenames_move_to_next (db_files);
351         }
352
353         while (notmuch_filenames_valid (db_subdirs) &&
354                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
355         {
356             const char *filename = notmuch_filenames_get (db_subdirs);
357
358             if (strcmp (filename, entry->d_name) < 0)
359             {
360                 char *absolute = talloc_asprintf (state->removed_directories,
361                                                   "%s/%s", path, filename);
362
363                 _filename_list_add (state->removed_directories, absolute);
364             }
365
366             notmuch_filenames_move_to_next (db_subdirs);
367         }
368
369         /* If we're looking at a symlink, we only want to add it if it
370          * links to a regular file, (and not to a directory, say).
371          *
372          * Similarly, if the file is of unknown type (due to filesytem
373          * limitations), then we also need to look closer.
374          *
375          * In either case, a stat does the trick.
376          */
377         if (entry->d_type == DT_LNK || entry->d_type == DT_UNKNOWN) {
378             int err;
379
380             next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
381             err = stat (next, &st);
382             talloc_free (next);
383             next = NULL;
384
385             /* Don't emit an error for a link pointing nowhere, since
386              * the directory-traversal pass will have already done
387              * that. */
388             if (err)
389                 continue;
390
391             if (! S_ISREG (st.st_mode))
392                 continue;
393         } else if (entry->d_type != DT_REG) {
394             continue;
395         }
396
397         /* Don't add a file that we've added before. */
398         if (notmuch_filenames_valid (db_files) &&
399             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
400         {
401             notmuch_filenames_move_to_next (db_files);
402             continue;
403         }
404
405         /* We're now looking at a regular file that doesn't yet exist
406          * in the database, so add it. */
407         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
408
409         state->processed_files++;
410
411         if (state->verbose) {
412             if (state->output_is_a_tty)
413                 printf("\r\033[K");
414
415             printf ("%i/%i: %s",
416                     state->processed_files,
417                     state->total_files,
418                     next);
419
420             putchar((state->output_is_a_tty) ? '\r' : '\n');
421             fflush (stdout);
422         }
423
424         status = notmuch_database_add_message (notmuch, next, &message);
425         switch (status) {
426         /* success */
427         case NOTMUCH_STATUS_SUCCESS:
428             state->added_messages++;
429             notmuch_message_freeze (message);
430             for (tag=state->new_tags; *tag != NULL; tag++)
431                 notmuch_message_add_tag (message, *tag);
432             if (state->synchronize_flags == TRUE)
433                 notmuch_message_maildir_flags_to_tags (message);
434             notmuch_message_thaw (message);
435             break;
436         /* Non-fatal issues (go on to next file) */
437         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
438             /* Defer sync of maildir flags until after old filenames
439              * are removed in the case of a rename. */
440             if (state->synchronize_flags == TRUE)
441                 _filename_list_add (state->message_ids_to_sync,
442                                     notmuch_message_get_message_id (message));
443             break;
444         case NOTMUCH_STATUS_FILE_NOT_EMAIL:
445             fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
446                      next);
447             break;
448         /* Fatal issues. Don't process anymore. */
449         case NOTMUCH_STATUS_READ_ONLY_DATABASE:
450         case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
451         case NOTMUCH_STATUS_OUT_OF_MEMORY:
452             fprintf (stderr, "Error: %s. Halting processing.\n",
453                      notmuch_status_to_string (status));
454             ret = status;
455             goto DONE;
456         default:
457         case NOTMUCH_STATUS_FILE_ERROR:
458         case NOTMUCH_STATUS_NULL_POINTER:
459         case NOTMUCH_STATUS_TAG_TOO_LONG:
460         case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
461         case NOTMUCH_STATUS_LAST_STATUS:
462             INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
463             goto DONE;
464         }
465
466         if (message) {
467             notmuch_message_destroy (message);
468             message = NULL;
469         }
470
471         if (do_print_progress) {
472             do_print_progress = 0;
473             generic_print_progress ("Processed", "files", state->tv_start,
474                                     state->processed_files, state->total_files);
475         }
476
477         talloc_free (next);
478         next = NULL;
479     }
480
481     if (interrupted)
482         goto DONE;
483
484     /* Now that we've walked the whole filesystem list, anything left
485      * over in the database lists has been deleted. */
486     while (notmuch_filenames_valid (db_files))
487     {
488         char *absolute = talloc_asprintf (state->removed_files,
489                                           "%s/%s", path,
490                                           notmuch_filenames_get (db_files));
491
492         _filename_list_add (state->removed_files, absolute);
493
494         notmuch_filenames_move_to_next (db_files);
495     }
496
497     while (notmuch_filenames_valid (db_subdirs))
498     {
499         char *absolute = talloc_asprintf (state->removed_directories,
500                                           "%s/%s", path,
501                                           notmuch_filenames_get (db_subdirs));
502
503         _filename_list_add (state->removed_directories, absolute);
504
505         notmuch_filenames_move_to_next (db_subdirs);
506     }
507
508     if (! interrupted) {
509         status = notmuch_directory_set_mtime (directory, fs_mtime);
510         if (status && ret == NOTMUCH_STATUS_SUCCESS)
511             ret = status;
512     }
513
514   DONE:
515     if (next)
516         talloc_free (next);
517     if (entry)
518         free (entry);
519     if (dir)
520         closedir (dir);
521     if (fs_entries)
522         free (fs_entries);
523     if (db_subdirs)
524         notmuch_filenames_destroy (db_subdirs);
525     if (db_files)
526         notmuch_filenames_destroy (db_files);
527     if (directory)
528         notmuch_directory_destroy (directory);
529
530     return ret;
531 }
532
533 static void
534 setup_progress_printing_timer (void)
535 {
536     struct sigaction action;
537     struct itimerval timerval;
538
539     /* Setup our handler for SIGALRM */
540     memset (&action, 0, sizeof (struct sigaction));
541     action.sa_handler = handle_sigalrm;
542     sigemptyset (&action.sa_mask);
543     action.sa_flags = SA_RESTART;
544     sigaction (SIGALRM, &action, NULL);
545
546     /* Then start a timer to send SIGALRM once per second. */
547     timerval.it_interval.tv_sec = 1;
548     timerval.it_interval.tv_usec = 0;
549     timerval.it_value.tv_sec = 1;
550     timerval.it_value.tv_usec = 0;
551     setitimer (ITIMER_REAL, &timerval, NULL);
552 }
553
554 static void
555 stop_progress_printing_timer (void)
556 {
557     struct sigaction action;
558     struct itimerval timerval;
559
560     /* Now stop the timer. */
561     timerval.it_interval.tv_sec = 0;
562     timerval.it_interval.tv_usec = 0;
563     timerval.it_value.tv_sec = 0;
564     timerval.it_value.tv_usec = 0;
565     setitimer (ITIMER_REAL, &timerval, NULL);
566
567     /* And disable the signal handler. */
568     action.sa_handler = SIG_IGN;
569     sigaction (SIGALRM, &action, NULL);
570 }
571
572
573 /* This is the top-level entry point for add_files. It does a couple
574  * of error checks and then calls into the recursive function. */
575 static notmuch_status_t
576 add_files (notmuch_database_t *notmuch,
577            const char *path,
578            add_files_state_t *state)
579 {
580     notmuch_status_t status;
581     struct stat st;
582
583     if (stat (path, &st)) {
584         fprintf (stderr, "Error reading directory %s: %s\n",
585                  path, strerror (errno));
586         return NOTMUCH_STATUS_FILE_ERROR;
587     }
588
589     if (! S_ISDIR (st.st_mode)) {
590         fprintf (stderr, "Error: %s is not a directory.\n", path);
591         return NOTMUCH_STATUS_FILE_ERROR;
592     }
593
594     status = add_files_recursive (notmuch, path, state);
595
596     return status;
597 }
598
599 /* XXX: This should be merged with the add_files function since it
600  * shares a lot of logic with it. */
601 /* Recursively count all regular files in path and all sub-directories
602  * of path.  The result is added to *count (which should be
603  * initialized to zero by the top-level caller before calling
604  * count_files). */
605 static void
606 count_files (const char *path, int *count)
607 {
608     struct dirent *entry = NULL;
609     char *next;
610     struct stat st;
611     struct dirent **fs_entries = NULL;
612     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
613     int i = 0;
614
615     if (num_fs_entries == -1) {
616         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
617                  path, strerror (errno));
618         goto DONE;
619     }
620
621     while (!interrupted) {
622         if (i == num_fs_entries)
623             break;
624
625         entry = fs_entries[i++];
626
627         /* Ignore special directories to avoid infinite recursion.
628          * Also ignore the .notmuch directory.
629          */
630         /* XXX: Eventually we'll want more sophistication to let the
631          * user specify files to be ignored. */
632         if (strcmp (entry->d_name, ".") == 0 ||
633             strcmp (entry->d_name, "..") == 0 ||
634             strcmp (entry->d_name, ".notmuch") == 0)
635         {
636             continue;
637         }
638
639         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
640             next = NULL;
641             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
642                      path, entry->d_name);
643             continue;
644         }
645
646         stat (next, &st);
647
648         if (S_ISREG (st.st_mode)) {
649             *count = *count + 1;
650             if (*count % 1000 == 0) {
651                 printf ("Found %d files so far.\r", *count);
652                 fflush (stdout);
653             }
654         } else if (S_ISDIR (st.st_mode)) {
655             count_files (next, count);
656         }
657
658         free (next);
659     }
660
661   DONE:
662     if (entry)
663         free (entry);
664     if (fs_entries)
665         free (fs_entries);
666 }
667
668 static void
669 upgrade_print_progress (void *closure,
670                         double progress)
671 {
672     add_files_state_t *state = closure;
673
674     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
675
676     if (progress > 0) {
677         struct timeval tv_now;
678         double elapsed, time_remaining;
679
680         gettimeofday (&tv_now, NULL);
681
682         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
683         time_remaining = (elapsed / progress) * (1.0 - progress);
684         printf (" (");
685         notmuch_time_print_formatted_seconds (time_remaining);
686         printf (" remaining)");
687     }
688
689     printf (".      \r");
690
691     fflush (stdout);
692 }
693
694 /* Recursively remove all filenames from the database referring to
695  * 'path' (or to any of its children). */
696 static void
697 _remove_directory (void *ctx,
698                    notmuch_database_t *notmuch,
699                    const char *path,
700                    int *renamed_files,
701                    int *removed_files)
702 {
703     notmuch_directory_t *directory;
704     notmuch_filenames_t *files, *subdirs;
705     notmuch_status_t status;
706     char *absolute;
707
708     directory = notmuch_database_get_directory (notmuch, path);
709
710     for (files = notmuch_directory_get_child_files (directory);
711          notmuch_filenames_valid (files);
712          notmuch_filenames_move_to_next (files))
713     {
714         absolute = talloc_asprintf (ctx, "%s/%s", path,
715                                     notmuch_filenames_get (files));
716         status = notmuch_database_remove_message (notmuch, absolute);
717         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
718             *renamed_files = *renamed_files + 1;
719         else
720             *removed_files = *removed_files + 1;
721         talloc_free (absolute);
722     }
723
724     for (subdirs = notmuch_directory_get_child_directories (directory);
725          notmuch_filenames_valid (subdirs);
726          notmuch_filenames_move_to_next (subdirs))
727     {
728         absolute = talloc_asprintf (ctx, "%s/%s", path,
729                                     notmuch_filenames_get (subdirs));
730         _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
731         talloc_free (absolute);
732     }
733
734     notmuch_directory_destroy (directory);
735 }
736
737 int
738 notmuch_new_command (void *ctx, int argc, char *argv[])
739 {
740     notmuch_config_t *config;
741     notmuch_database_t *notmuch;
742     add_files_state_t add_files_state;
743     double elapsed;
744     struct timeval tv_now, tv_start;
745     int ret = 0;
746     struct stat st;
747     const char *db_path;
748     char *dot_notmuch_path;
749     struct sigaction action;
750     _filename_node_t *f;
751     int renamed_files, removed_files;
752     notmuch_status_t status;
753     int i;
754     notmuch_bool_t timer_is_active = FALSE;
755
756     add_files_state.verbose = 0;
757     add_files_state.output_is_a_tty = isatty (fileno (stdout));
758
759     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
760         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
761             add_files_state.verbose = 1;
762         } else {
763             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
764             return 1;
765         }
766     }
767     config = notmuch_config_open (ctx, NULL, NULL);
768     if (config == NULL)
769         return 1;
770
771     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
772     add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
773     add_files_state.message_ids_to_sync = _filename_list_create (ctx);
774     db_path = notmuch_config_get_database_path (config);
775
776     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
777
778     if (stat (dot_notmuch_path, &st)) {
779         int count;
780
781         count = 0;
782         count_files (db_path, &count);
783         if (interrupted)
784             return 1;
785
786         printf ("Found %d total files (that's not much mail).\n", count);
787         notmuch = notmuch_database_create (db_path);
788         add_files_state.total_files = count;
789     } else {
790         notmuch = notmuch_database_open (db_path,
791                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
792         if (notmuch == NULL)
793             return 1;
794
795         if (notmuch_database_needs_upgrade (notmuch)) {
796             printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
797             gettimeofday (&add_files_state.tv_start, NULL);
798             notmuch_database_upgrade (notmuch, upgrade_print_progress,
799                                       &add_files_state);
800             printf ("Your notmuch database has now been upgraded to database format version %u.\n",
801                     notmuch_database_get_version (notmuch));
802         }
803
804         add_files_state.total_files = 0;
805     }
806
807     if (notmuch == NULL)
808         return 1;
809
810     /* Setup our handler for SIGINT. We do this after having
811      * potentially done a database upgrade we this interrupt handler
812      * won't support. */
813     memset (&action, 0, sizeof (struct sigaction));
814     action.sa_handler = handle_sigint;
815     sigemptyset (&action.sa_mask);
816     action.sa_flags = SA_RESTART;
817     sigaction (SIGINT, &action, NULL);
818
819     talloc_free (dot_notmuch_path);
820     dot_notmuch_path = NULL;
821
822     add_files_state.processed_files = 0;
823     add_files_state.added_messages = 0;
824     gettimeofday (&add_files_state.tv_start, NULL);
825
826     add_files_state.removed_files = _filename_list_create (ctx);
827     add_files_state.removed_directories = _filename_list_create (ctx);
828
829     if (! debugger_is_active () && add_files_state.output_is_a_tty
830         && ! add_files_state.verbose) {
831         setup_progress_printing_timer ();
832         timer_is_active = TRUE;
833     }
834
835     ret = add_files (notmuch, db_path, &add_files_state);
836
837     removed_files = 0;
838     renamed_files = 0;
839     gettimeofday (&tv_start, NULL);
840     for (f = add_files_state.removed_files->head; f; f = f->next) {
841         status = notmuch_database_remove_message (notmuch, f->filename);
842         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
843             renamed_files++;
844         else
845             removed_files++;
846         if (do_print_progress) {
847             do_print_progress = 0;
848             generic_print_progress ("Cleaned up", "messages",
849                 tv_start, removed_files + renamed_files,
850                 add_files_state.removed_files->count);
851         }
852     }
853
854     gettimeofday (&tv_start, NULL);
855     for (f = add_files_state.removed_directories->head, i = 0; f; f = f->next, i++) {
856         _remove_directory (ctx, notmuch, f->filename,
857                            &renamed_files, &removed_files);
858         if (do_print_progress) {
859             do_print_progress = 0;
860             generic_print_progress ("Cleaned up", "directories",
861                 tv_start, i,
862                 add_files_state.removed_directories->count);
863         }
864     }
865
866     talloc_free (add_files_state.removed_files);
867     talloc_free (add_files_state.removed_directories);
868
869     /* Now that removals are done (hence the database is aware of all
870      * renames), we can synchronize maildir_flags to tags for all
871      * messages that had new filenames appear on this run. */
872     gettimeofday (&tv_start, NULL);
873     if (add_files_state.synchronize_flags) {
874         _filename_node_t *node;
875         notmuch_message_t *message;
876         for (node = add_files_state.message_ids_to_sync->head, i = 0;
877              node;
878              node = node->next, i++)
879         {
880             message = notmuch_database_find_message (notmuch, node->filename);
881             notmuch_message_maildir_flags_to_tags (message);
882             notmuch_message_destroy (message);
883             if (do_print_progress) {
884                 do_print_progress = 0;
885                 generic_print_progress (
886                     "Synchronized tags for", "messages",
887                     tv_start, i, add_files_state.message_ids_to_sync->count);
888             }
889         }
890     }
891
892     talloc_free (add_files_state.message_ids_to_sync);
893     add_files_state.message_ids_to_sync = NULL;
894
895     if (timer_is_active)
896         stop_progress_printing_timer ();
897
898     gettimeofday (&tv_now, NULL);
899     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
900                                     tv_now);
901
902     if (add_files_state.processed_files) {
903         printf ("Processed %d %s in ", add_files_state.processed_files,
904                 add_files_state.processed_files == 1 ?
905                 "file" : "total files");
906         notmuch_time_print_formatted_seconds (elapsed);
907         if (elapsed > 1) {
908             printf (" (%d files/sec.).\033[K\n",
909                     (int) (add_files_state.processed_files / elapsed));
910         } else {
911             printf (".\033[K\n");
912         }
913     }
914
915     if (add_files_state.added_messages) {
916         printf ("Added %d new %s to the database.",
917                 add_files_state.added_messages,
918                 add_files_state.added_messages == 1 ?
919                 "message" : "messages");
920     } else {
921         printf ("No new mail.");
922     }
923
924     if (removed_files) {
925         printf (" Removed %d %s.",
926                 removed_files,
927                 removed_files == 1 ? "message" : "messages");
928     }
929
930     if (renamed_files) {
931         printf (" Detected %d file %s.",
932                 renamed_files,
933                 renamed_files == 1 ? "rename" : "renames");
934     }
935
936     printf ("\n");
937
938     if (ret) {
939         printf ("\nNote: At least one error was encountered: %s\n",
940                 notmuch_status_to_string (ret));
941     }
942
943     notmuch_database_close (notmuch);
944
945     return ret || interrupted;
946 }