/* These routines implement a logging facility which can send its
 * messages either to the console or across the net or both.
 * Currently it depends on the version of printf being used with the
 * VAX.  This printf should probably be used on any machine anyway.
 */

#include <types.h>
#include <sys.h>
#include <mosu.h>
#include "../../gw/src/defs.h"
#include "../../gw/src/macs.h"
#include "../../gw/src/net.h"
#include "../../gw/src/ext.h"
#include "../../lib.vax/stdio.h"

/* Parameters */
#define LOGPKTLEN 256		/* Max data length in packet */
#define LOGMSGLEN 128		/* Maximum message length */

iorb *log_iob;			/* I/O buffer for logging messages */
byte *log_msgp;			/* Pointer to where next message goes */
unss log_len;			/* Length of messages */
char log_msg[LOGMSGLEN];	/* Storage for the message */
unsf log_missed;		/* Counts number of missed log
				 * messages because couldn't alloc iob */
ext bitf logflg;		/* Where messages should be logged */
#define LOG_CON 1		/* log to console */
#define LOG_NET 2		/* log to network */

log_init()
{
    log_iob = NULL;
    log_missed = 0;
    log_len = 0;
}

dolog(fmt, args)
char *fmt;
int args;
{
    intf msg_len;

    if (logflg) {
	FILE fil;

	fil.f_count = LOGMSGLEN;
	fil.f_buf = log_msg;
	_doprnt(fmt, &args, &fil);
	*(fil.f_buf) = '\0';
	msg_len = LOGMSGLEN - fil.f_count;
    }

    if (logflg & LOG_CON)
      puts(log_msg);

    if (logflg & LOG_NET) {
	if (log_len + msg_len > LOGPKTLEN) {
	    send_log(log_iob);
	    log_iob = NULL;
	}
	if (log_iob == NULL) {
	    if ((log_iob = getbuf(bufsiz)) == NULL) {
		log_missed++;
		return;
	    }
	    log_msgp = log_iob->i_addr = ((byte *)log_iob) + pktoff;
	    log_len = 0;
	}
	strcpy(log_msgp, log_msg, msg_len);
	log_msgp += msg_len;
	log_len += msg_len;
    }
}
