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