#include "biffer.h"
/* #include "options.h" */
#include <sys/param.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <syslog.h>
#include <ctype.h>
#include <sys/time.h>
#include <utmp.h>
/* #include <mfcf/libuw/userid.h> */


useBiffer( name, file, offset, folder )
	char *name;
	char *file;
	int offset;
	int folder;
{
	char buf[MAXPATHLEN];
	struct passwd *pw;
	struct stat sbuf;
	int sock;
	int statok;
	FILE *fp, *mfp;
	static struct sockaddr_in sin;
	static int init = 0;

	pw = getpwnam( name );
	if (pw == NULL) /* but he just got mail!! oh well */
		return( FALSE );
	strcpy( buf, pw->pw_dir );
	strcat( buf, BIFFRC );
	if ( stat( buf, &sbuf ) == -1 )	/* no BIFFRC */
		return( FALSE );
	/* BIFFRC exists, but it's not necessarily a file, but who cares?? */

	if (init == 0) {
		struct servent *sp;
		struct hostent *hp;

		sp = getservbyname( SERVICE, "tcp" );
		hp = gethostbyname( "localhost" );
		if (sp == NULL || hp == NULL) {
			init = -1;
			return( FALSE );
		}
		memset( (char *)&sin, '\0', sizeof(sin) );
		memcpy( (char *)&sin.sin_addr, hp->h_addr, hp->h_length );
		sin.sin_family	= hp->h_addrtype;
		sin.sin_port	= sp->s_port;
		init = 1;
	}
	if (init < 0)
		return FALSE;
	sock = socket( sin.sin_family, SOCK_STREAM, 0 );
	if (sock < 0)
		return( FALSE );
	if (connect( sock, (struct sockaddr *)&sin, sizeof(sin) ) < 0 ||
	    (fp = fdopen(sock,"w")) == NULL) {
		(void) close( sock );
		return( FALSE );
	}
	/* stat the mailbox so that we can reset the access time after
	   we read it */
	statok = ( stat( name, &sbuf ) == -1 ) ? FALSE : TRUE;
	if ( (mfp = fopen( name, "r" )) == NULL) {	/* ? */
		fclose(fp);
		return FALSE;
	}
	/* now write the stream to the biffer */
	fprintf( fp, "%s\n", name );
	fprintf( fp, "%s\n", name );
	fprintf( fp, "\n" );		/* machine */
	fprintf( fp, "0\n" );
	fprintf( fp, "%s\n", "MESSAGE FOLLOWS" );
	fseek( mfp, offset, SEEK_SET );
	if ( fgets( buf, sizeof(buf), mfp ) != NULL ) {
		fputs( buf, fp );
		while ( fgets( buf, sizeof(buf), mfp ) != NULL ) {
			if ( strncmp( "From ", buf, 5 ) == 0 )
				break;
			fputs( buf, fp );
		}
	}
	fclose( mfp );
	/* now set the mailbox access time back the way it was, so that
	   "You have new mail" will work again */
	if ( statok ) {
	    struct timeval tv[2];
	    tv[0].tv_sec = sbuf.st_atime;
	    tv[0].tv_usec = 0;
	    tv[1].tv_sec = sbuf.st_mtime;
	    tv[1].tv_usec = 0;
	    (void) utimes( name, tv );	/* don't care if it fails */
	}
	fclose( fp );
	return( TRUE );
}
