712e173d0325cce5755e49e92444970696d622e5
[mmh] / sbr / m_draft.c
1
2 /*
3  * m_draft.c -- construct the name of a draft message
4  *
5  * $Id$
6  */
7
8 #include <h/mh.h>
9 #include <errno.h>
10
11 extern int errno;
12
13
14 char *
15 m_draft (char *folder, char *msg, int use, int *isdf)
16 {
17     register char *cp;
18     register struct msgs *mp;
19     struct stat st;
20     static char buffer[BUFSIZ];
21
22     if (*isdf == -1 || folder == NULL || *folder == '\0') {
23         if (*isdf == -1 || (cp = context_find ("Draft-Folder")) == NULL) {
24             *isdf = 0;
25             return m_maildir (msg && *msg ? msg : draft);
26         } else {
27             folder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp,
28                     *cp != '@' ? TFOLDER : TSUBCWF);
29         }
30     }
31     *isdf = 1;
32     
33     chdir (m_maildir (""));
34     strncpy (buffer, m_maildir (folder), sizeof(buffer));
35     if (stat (buffer, &st) == -1) {
36         if (errno != ENOENT)
37             adios (buffer, "error on folder");
38         cp = concat ("Create folder \"", buffer, "\"? ", NULL);
39         if (!getanswer (cp))
40             done (0);
41         free (cp);
42         if (!makedir (buffer))
43             adios (NULL, "unable to create folder %s", buffer);
44     }
45
46     if (chdir (buffer) == -1)
47         adios (buffer, "unable to change directory to");
48
49     if (!(mp = folder_read (folder)))
50         adios (NULL, "unable to read folder %s", folder);
51
52     /*
53      * Make sure we have enough message status space for all
54      * the message numbers from 1 to "new", since we might
55      * select an empty slot.  If we add more space at the
56      * end, go ahead and add 10 additional slots.
57      */
58     if (mp->hghmsg >= mp->hghoff) {
59         if (!(mp = folder_realloc (mp, 1, mp->hghmsg + 10)))
60             adios (NULL, "unable to allocate folder storage");
61     } else if (mp->lowoff > 1) {
62         if (!(mp = folder_realloc (mp, 1, mp->hghoff)))
63             adios (NULL, "unable to allocate folder storage");
64     }
65
66     mp->msgflags |= ALLOW_NEW;  /* allow the "new" sequence */
67
68     /*
69      * If we have been give a valid message name, then use that.
70      * Else, if we are given the "use" option, then use the
71      * current message.  Else, use special sequence "new".
72      */
73     if (!m_convert (mp, msg && *msg ? msg : use ? "cur" : "new"))
74         done (1);
75     seq_setprev (mp);
76
77     if (mp->numsel > 1)
78         adios (NULL, "only one message draft at a time!");
79
80     snprintf (buffer, sizeof(buffer), "%s/%s", mp->foldpath, m_name (mp->lowsel));
81     cp = buffer;
82
83     seq_setcur (mp, mp->lowsel);/* set current message for folder */
84     seq_save (mp);              /* synchronize message sequences  */
85     folder_free (mp);           /* free folder/message structure  */
86
87     return cp;
88 }