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