/* $Cambridge: hermes/src/prayer/cmd/cmd_download.c,v 1.4 2010/07/07 15:49:34 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "prayer_session.h"

/* ====================================================================== */

void cmd_download(struct session *session)
{
    struct request *request = session->request;
    struct msgmap *zm = session->zm;
    unsigned long msgno, msguid;
    char *text, *s;
    unsigned long len;
    MAILSTREAM *stream = session->stream;
    struct buffer *b = request->write_buffer;

    if (request->argc >= 3) {
        msgno = atoi(request->argv[1]);
        msguid = atoi(request->argv[2]);

        if (!(msgno = stream_check_uid(session, stream, msgno, msguid))) {
            session_redirect(session, request, "restart");
            return;
        }
    } else {
        msgno = session->last_displayed;

        if ((msgno == 0) || (msgno > zm->nmsgs))
            msgno = msgmap_value(session->zm, msgmap_size(session->zm));

        msguid = ml_uid(session, stream, msgno);
    }

    session->current = msgno;
    session->last_displayed = msgno;


    if (msgno == 0) {
        session_redirect(session, request, "error");
        return;
    }

    if (!(text =
          ml_fetch_header(session, stream, msgno, NIL, NIL, &len, 0)))
    {
        session_redirect(session, request, "restart");
        return;
    }

    s = text;
    while (*s) {
        if ((*s == '\015') || (*s == '\012')) {
            s += ((s[0] == '\015') && (s[1] == '\012')) ? 2 : 1;
            bputc(b, '\n');
        } else
            bputc(b, *s++);
    }

    if (!(text = ml_fetch_text(session, stream, msgno, NIL, &len, 0))) {
        session_redirect(session, request, "restart");
        return;
    }
    /* Don't free(text): lives in c-client message cache */

    s = text;
    while (*s) {
        if ((*s == '\015') || (*s == '\012')) {
            s += ((s[0] == '\015') && (s[1] == '\012')) ? 2 : 1;
            bputc(b, '\n');
        } else
            bputc(b, *s++);
    }

    /* Send out the response */
    response_text(request, 200);
}
