/*
 *
 *  AM --- AmigaMail
 *  (C) 1991, 1992 by Christian Riede
 *
 *  AM is distributed in the hope that it will be useful, but WITHOUT ANY
 *  WARRANTY.  No author or distributor accepts responsibility to anyone
 *  for the consequences of using it or for whether it serves any
 *  particular purpose or works at all, unless he says so in writing.
 *  Refer to the GNU General Public License, Version 1, for full details.
 *  
 *  Everyone is granted permission to copy, modify and redistribute AM,
 *  but only under the conditions described in the GNU General Public
 *  License, Version 1.  A copy of this license is supposed to have been 
 *  given to you along with AM so you can know your rights and responsi-
 *  bilities.  It should be in a file named COPYING.  Among other things,
 *  the copyright notice and this notice must be preserved on all copies.
 *
 *  
 *
 */

#include "am.h"
#include "server.h"

/* write contents into UUMAIL:<username>.mail/contents */
int WriteContents(char *folder,struct List *Mailbox,struct Strings *Strings)
{
	struct ContentsItem Actual;
	BPTR Contents;
	char ContentsName1[MAIL_FIELDLENGTH];
	char ContentsName2[MAIL_FIELDLENGTH];
	struct Mail *Mail;

	/* build name of new contents file */
	sprintf(ContentsName1,"%s/contents.new",folder);

	/* open contents file */
	if (!(Contents = Open((UBYTE *)ContentsName1,MODE_NEWFILE)))
		return(FALSE);

	if (!(WriteStrings(Contents,Strings)))
	{
		Close(Contents);
		return(FALSE);
	}

	/* write contents file */
	while (Mail = (struct Mail *)RemTail(Mailbox))
	{
		Actual.Number = Mail->Number;
		Actual.FromNumber = GetNumber(Mail->From,FALSE,Strings);
		Actual.ToNumber = GetNumber(Mail->To,FALSE,Strings);
		Actual.CcNumber = GetNumber(Mail->Cc,FALSE,Strings);
		Actual.ReplyToNumber = GetNumber(Mail->ReplyTo,FALSE,Strings);
		Actual.SubjectNumber = GetNumber(Mail->Subject,FALSE,Strings);
		Actual.MsgIdNumber = GetNumber(Mail->MsgId,FALSE,Strings);
		Actual.InReplyToNumber = GetNumber(Mail->InReplyTo,FALSE,Strings);
		Actual.Date = Mail->Date;
		Actual.read = Mail->read;
		
		/* use buffered IO */

		if (FWrite(Contents,&Actual,1,sizeof(struct ContentsItem))!=
			sizeof(struct ContentsItem))
		{	
			Close(Contents);
			return(FALSE);
		}

		/* free it */
		FreeMail(Mail);
	}

	/* close contents file */
	Close(Contents);

	/* free strings */
	FreeStrings(Strings);

	/* build name of old contents file */
	sprintf(ContentsName1,"%s/contents.old",folder);

	/* delete it */
	DeleteFile((UBYTE *)ContentsName1);
	
	/* build name of actual contents file */
	sprintf(ContentsName2,"%s/contents",folder);

	/* rename actual as old */
	Rename((UBYTE *)ContentsName2,(UBYTE *)ContentsName1);

	/* build name of new contents file */
	sprintf(ContentsName1,"%s/contents.new",folder);

	/* rename new as actual */
	Rename((UBYTE *)ContentsName1,(UBYTE *)ContentsName2);

	return(TRUE);
}

