/*
 * this file is a part of yabbs - yet another bulletin board system.
 * Copyright (C) 1993, 1994 Alex Wetmore.  
 * email: alex@phred.org
 * address: 6 rech ave
 *          oreland pa 19075
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include "bbs_struct.h"
#include "bbs_files.h"

void main(int argc, char **argv) {
    FILE *fmsg, *fidx, *funix;
    irec idx;
    mrec msg;
    unsigned long i;
    char fn_idx[1024], fn_msg[1024], fn_unix[1024];

    if (argc != 3) {
        printf("usage: yabbs2mail <yabbs data file> <unix mail file>\n");
        printf("  converts yabbs message files to unix (elm) message files\n");
        exit(1);
    }

    strcpy(fn_msg, argv[1]);
    strcat(fn_msg, ".msg");
    strcpy(fn_idx, argv[1]);
    strcat(fn_idx, ".idx");
    strcpy(fn_unix, argv[2]);

    if ((fmsg = fopen(fn_msg, "rb")) == NULL) {
        perror("makeidx: error opening yabbs message data file for read");
        exit(1);
    }

    if ((fidx = fopen(fn_idx, "rb")) == NULL) {
        perror("makeidx: error opening yabbs index data file for read");
        exit(1);
    }

    if ((funix = fopen(fn_unix, "wb")) == NULL) {
        perror("makeidx: error opening unix message file for write");
        exit(1);
    }

    i = 0;
    while (fread(&idx, sizeof(irec), 1, fidx) == 1) {
        fread(msg.to, 9, 1, fmsg);
        fread(msg.from, 9, 1, fmsg);
        fread(msg.title, 33, 1, fmsg);
        fread(msg.time, 32, 1, fmsg);
        fread(&msg.deleted, 1, 1, fmsg);
        fread(msg.msg, idx.length - HDRLEN, 1, fmsg);

        if (msg.deleted != 'Y') {
            fprintf(funix, "From %s@yabbs %s\n", msg.from, msg.time);
            fprintf(funix, "From: %s@yabbs\n", msg.from);
            fprintf(funix, "To: %s@yabbs\n", msg.to);
            fprintf(funix, "Subject: %s\n", msg.title);
            fprintf(funix, "Date: %s\n", msg.time);
            msg.msg[idx.length - HDRLEN] = 0;
            fprintf(funix, "\n%s\n", msg.msg);
        }

        printf("yabbs2mail %s: %i (%i)      \r", fn_msg, i++, idx.length);
    }

    printf("\nwrote %i messages to %s\n", i - 1, fn_unix);

    fclose(fmsg);
    fclose(fidx);
    fclose(funix);
}
