Added external program hooks.
[mmh] / uip / refile.c
1
2 /*
3  * refile.c -- move or link message(s) from a source folder
4  *          -- into one or more destination folders
5  *
6  * $Id$
7  *
8  * This code is Copyright (c) 2002, by the authors of nmh.  See the
9  * COPYRIGHT file in the root directory of the nmh distribution for
10  * complete copyright information.
11  */
12
13 #include <h/mh.h>
14 #include <fcntl.h>
15 #include <errno.h>
16
17 /*
18  * We allocate spaces for messages (msgs array)
19  * this number of elements at a time.
20  */
21 #define MAXMSGS  256
22
23
24 static struct swit switches[] = {
25 #define DRAFTSW          0
26     { "draft", 0 },
27 #define LINKSW           1
28     { "link", 0 },
29 #define NLINKSW          2
30     { "nolink", 0 },
31 #define PRESSW           3
32     { "preserve", 0 },
33 #define NPRESSW          4
34     { "nopreserve", 0 },
35 #define UNLINKSW         5
36     { "unlink", 0 },
37 #define NUNLINKSW        6
38     { "nounlink", 0 },
39 #define SRCSW            7
40     { "src +folder", 0 },
41 #define FILESW           8
42     { "file file", 0 },
43 #define RPROCSW          9
44     { "rmmproc program", 0 },
45 #define NRPRCSW         10
46     { "normmproc", 0 },
47 #define VERSIONSW       11
48     { "version", 0 },
49 #define HELPSW          12
50     { "help", 0 },
51     { NULL, 0 }
52 };
53
54 extern int errno;
55
56 static char maildir[BUFSIZ];
57
58 struct st_fold {
59     char *f_name;
60     struct msgs *f_mp;
61 };
62
63 /*
64  * static prototypes
65  */
66 static void opnfolds (struct st_fold *, int);
67 static void clsfolds (struct st_fold *, int);
68 static void remove_files (int, char **);
69 static int m_file (char *, struct st_fold *, int, int, int);
70
71
72 int
73 main (int argc, char **argv)
74 {
75     int linkf = 0, preserve = 0, filep = 0;
76     int foldp = 0, isdf = 0, unlink_msgs = 0;
77     int i, msgnum, nummsgs, maxmsgs;
78     char *cp, *folder = NULL, buf[BUFSIZ];
79     char **argp, **arguments, **msgs;
80     char *filevec[NFOLDERS + 2];
81     char **files = &filevec[1];    /* leave room for remove_files:vec[0] */
82     struct st_fold folders[NFOLDERS + 1];
83     struct msgs *mp;
84
85 #ifdef LOCALE
86     setlocale(LC_ALL, "");
87 #endif
88     invo_name = r1bindex (argv[0], '/');
89
90     /* read user profile/context */
91     context_read();
92
93     arguments = getarguments (invo_name, argc, argv, 1);
94     argp = arguments;
95
96     /*
97      * Allocate the initial space to record message
98      * names, ranges, and sequences.
99      */
100     nummsgs = 0;
101     maxmsgs = MAXMSGS;
102     if (!(msgs = (char **) malloc ((size_t) (maxmsgs * sizeof(*msgs)))))
103         adios (NULL, "unable to allocate storage");
104
105     /*
106      * Parse arguments
107      */
108     while ((cp = *argp++)) {
109         if (*cp == '-') {
110             switch (smatch (++cp, switches)) {
111             case AMBIGSW: 
112                 ambigsw (cp, switches);
113                 done (1);
114             case UNKWNSW: 
115                 adios (NULL, "-%s unknown\n", cp);
116
117             case HELPSW: 
118                 snprintf (buf, sizeof(buf), "%s [msgs] [switches] +folder ...",
119                           invo_name);
120                 print_help (buf, switches, 1);
121                 done (1);
122             case VERSIONSW:
123                 print_version(invo_name);
124                 done (1);
125
126             case LINKSW: 
127                 linkf++;
128                 continue;
129             case NLINKSW: 
130                 linkf = 0;
131                 continue;
132
133             case PRESSW: 
134                 preserve++;
135                 continue;
136             case NPRESSW: 
137                 preserve = 0;
138                 continue;
139
140             case UNLINKSW:
141                 unlink_msgs++;
142                 continue;
143             case NUNLINKSW:
144                 unlink_msgs = 0;
145                 continue;
146
147             case SRCSW: 
148                 if (folder)
149                     adios (NULL, "only one source folder at a time!");
150                 if (!(cp = *argp++) || *cp == '-')
151                     adios (NULL, "missing argument to %s", argp[-2]);
152                 folder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp,
153                                *cp != '@' ? TFOLDER : TSUBCWF);
154                 continue;
155             case DRAFTSW:
156                 if (filep > NFOLDERS)
157                     adios (NULL, "only %d files allowed!", NFOLDERS);
158                 isdf = 0;
159                 files[filep++] = getcpy (m_draft (NULL, NULL, 1, &isdf));
160                 continue;
161             case FILESW: 
162                 if (filep > NFOLDERS)
163                     adios (NULL, "only %d files allowed!", NFOLDERS);
164                 if (!(cp = *argp++) || *cp == '-')
165                     adios (NULL, "missing argument to %s", argp[-2]);
166                 files[filep++] = path (cp, TFILE);
167                 continue;
168
169             case RPROCSW: 
170                 if (!(rmmproc = *argp++) || *rmmproc == '-')
171                     adios (NULL, "missing argument to %s", argp[-2]);
172                 continue;
173             case NRPRCSW: 
174                 rmmproc = NULL;
175                 continue;
176             }
177         }
178         if (*cp == '+' || *cp == '@') {
179             if (foldp > NFOLDERS)
180                 adios (NULL, "only %d folders allowed!", NFOLDERS);
181             folders[foldp++].f_name =
182                 path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
183         } else {
184             /*
185              * Check if we need to allocate more space
186              * for message names, ranges, and sequences.
187              */
188             if (nummsgs >= maxmsgs) {
189                 maxmsgs += MAXMSGS;
190                 if (!(msgs = (char **) realloc (msgs,
191                                                 (size_t) (maxmsgs * sizeof(*msgs)))))
192                     adios (NULL, "unable to reallocate msgs storage");
193             }
194             msgs[nummsgs++] = cp;
195         }
196     }
197
198     if (!context_find ("path"))
199         free (path ("./", TFOLDER));
200     if (foldp == 0)
201         adios (NULL, "no folder specified");
202
203 #ifdef WHATNOW
204     if (!nummsgs && !foldp && !filep && (cp = getenv ("mhdraft")) && *cp)
205         files[filep++] = cp;
206 #endif /* WHATNOW */
207
208     /*
209      * We are refiling a file to the folders
210      */
211     if (filep > 0) {
212         if (folder || nummsgs)
213             adios (NULL, "use -file or some messages, not both");
214         opnfolds (folders, foldp);
215         for (i = 0; i < filep; i++)
216             if (m_file (files[i], folders, foldp, preserve, 0))
217                 done (1);
218         /* If -nolink, then "remove" files */
219         if (!linkf)
220             remove_files (filep, filevec);
221         done (0);
222     }
223
224     if (!nummsgs)
225         msgs[nummsgs++] = "cur";
226     if (!folder)
227         folder = getfolder (1);
228     strncpy (maildir, m_maildir (folder), sizeof(maildir));
229
230     if (chdir (maildir) == NOTOK)
231         adios (maildir, "unable to change directory to");
232
233     /* read source folder and create message structure */
234     if (!(mp = folder_read (folder)))
235         adios (NULL, "unable to read folder %s", folder);
236
237     /* check for empty folder */
238     if (mp->nummsg == 0)
239         adios (NULL, "no messages in %s", folder);
240
241     /* parse the message range/sequence/name and set SELECTED */
242     for (msgnum = 0; msgnum < nummsgs; msgnum++)
243         if (!m_convert (mp, msgs[msgnum]))
244             done (1);
245     seq_setprev (mp);   /* set the previous-sequence */
246
247     /* create folder structures for each destination folder */
248     opnfolds (folders, foldp);
249
250     /* Link all the selected messages into destination folders.
251      *
252      * This causes the add hook to be run for messages that are
253      * linked into another folder.  The refile hook is run for
254      * messages that are moved to another folder.
255      */
256     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
257         if (is_selected (mp, msgnum)) {
258             cp = getcpy (m_name (msgnum));
259             if (m_file (cp, folders, foldp, preserve, !linkf))
260                 done (1);
261             free (cp);
262         }
263     }
264
265     /*
266      * This is a hack.  If we are using an external rmmproc,
267      * then save the current folder to the context file,
268      * so the external rmmproc will remove files from the correct
269      * directory.  This should be moved to folder_delmsgs().
270      */
271     if (rmmproc) {
272         context_replace (pfolder, folder);
273         context_save ();
274         fflush (stdout);
275     }
276
277     /* If -nolink, then "remove" messages from source folder.
278      *
279      * Note that folder_delmsgs does not call the delete hook
280      * because the message has already been handled above.
281      */
282     if (!linkf) {
283         folder_delmsgs (mp, unlink_msgs, 1);
284     }
285
286     clsfolds (folders, foldp);
287
288     if (mp->hghsel != mp->curmsg
289         && (mp->numsel != mp->nummsg || linkf))
290         seq_setcur (mp, mp->hghsel);
291     seq_save (mp);      /* synchronize message sequences */
292
293     context_replace (pfolder, folder);  /* update current folder   */
294     context_save ();                    /* save the context file   */
295     folder_free (mp);                   /* free folder structure   */
296     return done (0);
297 }
298
299
300 /*
301  * Read all the destination folders and
302  * create folder structures for all of them.
303  */
304
305 static void
306 opnfolds (struct st_fold *folders, int nfolders)
307 {
308     register char *cp;
309     char nmaildir[BUFSIZ];
310     register struct st_fold *fp, *ep;
311     register struct msgs *mp;
312     struct stat st;
313
314     for (fp = folders, ep = folders + nfolders; fp < ep; fp++) {
315         chdir (m_maildir (""));
316         strncpy (nmaildir, m_maildir (fp->f_name), sizeof(nmaildir));
317
318         if (stat (nmaildir, &st) == NOTOK) {
319             if (errno != ENOENT)
320                 adios (nmaildir, "error on folder");
321             cp = concat ("Create folder \"", nmaildir, "\"? ", NULL);
322             if (!getanswer (cp))
323                 done (1);
324             free (cp);
325             if (!makedir (nmaildir))
326                 adios (NULL, "unable to create folder %s", nmaildir);
327         }
328
329         if (chdir (nmaildir) == NOTOK)
330             adios (nmaildir, "unable to change directory to");
331         if (!(mp = folder_read (fp->f_name)))
332             adios (NULL, "unable to read folder %s", fp->f_name);
333         mp->curmsg = 0;
334
335         fp->f_mp = mp;
336
337         chdir (maildir);
338     }
339 }
340
341
342 /*
343  * Set the Previous-Sequence and then sychronize the
344  * sequence file, for each destination folder.
345  */
346
347 static void
348 clsfolds (struct st_fold *folders, int nfolders)
349 {
350     register struct st_fold *fp, *ep;
351     register struct msgs *mp;
352
353     for (fp = folders, ep = folders + nfolders; fp < ep; fp++) {
354         mp = fp->f_mp;
355         seq_setprev (mp);
356         seq_save (mp);
357     }
358 }
359
360
361 /*
362  * If you have a "rmmproc" defined, we called that
363  * to remove all the specified files.  If "rmmproc"
364  * is not defined, then just unlink the files.
365  */
366
367 static void
368 remove_files (int filep, char **files)
369 {
370     int i;
371     char **vec;
372
373     /* If rmmproc is defined, we use that */
374     if (rmmproc) {
375         vec = files++;          /* vec[0] = filevec[0] */
376         files[filep] = NULL;    /* NULL terminate list */
377
378         fflush (stdout);
379         vec[0] = r1bindex (rmmproc, '/');
380         execvp (rmmproc, vec);
381         adios (rmmproc, "unable to exec");
382     }
383
384     /* Else just unlink the files */
385     files++;    /* advance past filevec[0] */
386     for (i = 0; i < filep; i++) {
387         if (unlink (files[i]) == NOTOK)
388             admonish (files[i], "unable to unlink");
389     }
390 }
391
392
393 /*
394  * Link (or copy) the message into each of
395  * the destination folders.
396  */
397
398 static int
399 m_file (char *msgfile, struct st_fold *folders, int nfolders, int preserve, int refile)
400 {
401     int msgnum;
402     struct st_fold *fp, *ep;
403
404     for (fp = folders, ep = folders + nfolders; fp < ep; fp++) {
405         if ((msgnum = folder_addmsg (&fp->f_mp, msgfile, 1, 0, preserve, nfolders == 1 && refile)) == -1)
406             return 1;
407     }
408     return 0;
409 }