#ifndef lint
static char *RCSid = "$Header: /fsys4/usr/source/users/msg/Common/RCS/answerback.c,v 1.2 90/12/29 21:59:53 jmsellen Exp $";
#endif

#if 0
/*
 * $Log:	answerback.c,v $
 * Revision 1.2  90/12/29  21:59:53  jmsellen
 * Use ANSBACK define from Include/msg.h
 * 
 * Revision 1.1  87/08/06  19:06:19  sahayman
 * Initial revision
 * 
 */
#endif

/* answerback.c
   Return a user's answerback message to the person who sent him a
   message.
*/

#include "msg.h"
#include <pwd.h>

#define MYBUFSIZ	(BUFSIZ/2)	/* BUFSIZ is max errmsg size */


/* We may be sending to multiple instances of the same user, so it makes
   since to remember the last user we looked up and his/her UID to avoid
   searching the passwd file again. */

answerback( errcode, user, line )
int errcode;
char *user;
char *line;
{
    static char lastuser[25];	/* too hard to use sizeof() */
    static int lastuid = -1;
    struct stat sbuf;
    FILE *fp;
    char answerbuf[sizeof(ANSBACK)+25];  /* lots of extra room */
    /* find name of answerback file */
    (void) sprintf( answerbuf, "%s%s", ANSBACK, line );
    /* Now make sure that if the answerback file exists, it belongs to
       the user we're sending to */
    if ( stat( answerbuf, &sbuf ) == -1 )
	return;		/* no answerback exists */
#if vms

#else
    if ( strcmp( user, lastuser ) != 0 ) {
	/* we don't know this guy, so look him up */
	struct passwd *pw = getpwnam( user );
	endpwent();
	if ( pw == (struct passwd *)NULL )
	    /* I know this guy exists, but ignore it */
	    return;
	(void) strcpy( lastuser, user );
	lastuid = pw->pw_uid;
    }
    if ( sbuf.st_uid != lastuid )
	return;		/* not his file */
#endif
    /* we don't care if we can't read his message - it's his problem */
    if ( (fp=fopen(answerbuf,"r")) != FPNULL ) {
	char buf[MYBUFSIZ+1];
	int len;
	if ( (len=fread( buf, 1, MYBUFSIZ, fp )) > 0 ) {
	    if ( buf[len-1] =='\n' ) len--;
	    buf[len] = '\0'; /* make it terminated */
	    if ( errcode == ANS_WARN )
		errmsg( errcode, user, line, buf );
	    else
		errmsg( errcode, user, hostname, line, buf );
	}
	(void) fclose( fp );
    }
}
