#include "global.h"
#include "commands.h"
#include "netuser.h"
#ifndef MSDOS
#include <time.h>
#include "ctype.h"
#include "session.h"
#endif
#ifdef MESSAGESERVER


#if !defined(_lint)
static char rcsid[] OPTIONAL = "$Id: message.c,v 1.2 1997/05/24 22:13:02 root Exp $";
#endif

#define MAXMESSAGEPORTS 10
struct m_portsused {
	int	port;
	int	sock;
	uint32	address;
	char	*message;
};
static struct m_portsused ports[MAXMESSAGEPORTS];

static void messageserv (int s, void *v1, void *p OPTIONAL);



/* Start up the message service */
int
message1 (int argc, char *argv[], void *p OPTIONAL)
{
int port, k;
uint32 address = INADDR_ANY;

	port = atoi(argv[1]);

	if (argc > 3)	{
		address = resolve (argv[3]);
		if (address == 0L)	{
			tprintf ("IP address %s does NOT resolve! MESSAGE server NOT started on port %d!\n",
				argv[3], port);
			return 0;
		}
	}

	for (k = 0; k < MAXMESSAGEPORTS; k++) {
		if (ports[k].port == port && ports[k].address == address)	{
			tprintf ("Sorry, but you already have a MESSAGE server on port #%d for that address!\n", port);
			return 0;
		}
	}

	for (k = 0; k < MAXMESSAGEPORTS; k++) {
		if (ports[k].sock <= 0)
			break;
	}
	if (k == MAXMESSAGEPORTS)	{
		tprintf ("Sorry, but all %d MESSAGE ports are assigned!\n", MAXMESSAGEPORTS);
		return 0;
	}

	ports[k].message = strdup (argv[2]);
	ports[k].sock = -1;
	ports[k].port = port;
	ports[k].address = address;

	return (installserver (argc, argv, &ports[k].sock, "MESSAGE Listener", ports[k].port,
		ports[k].address, "MESSAGE Server", messageserv, 1024, (void *)k));
}



int
message0 (int argc OPTIONAL, char *argv[] OPTIONAL, void *p OPTIONAL)
{
int port, k;
uint32 address = INADDR_ANY;

	port = atoi(argv[1]);
	if (argc > 2)	{
		address = resolve (argv[2]);
		if (address == 0L)	{
			tprintf ("IP address %s does NOT resolve! MESSAGE server NOT stopped on port %d!\n",
				argv[2], port);
			return 0;
		}
	}
	for (k = 0; k < MAXMESSAGEPORTS; k++) {
		if (ports[k].port == port && ports[k].address == address)	{
			ports[k].port = 0;
			free (ports[k].message);
			ports[k].message = NULLCHAR;
			return (deleteserver (&ports[k].sock));
		}
	}
	tprintf ("Sorry, but no MESSAGE server was found on port #%d for that address!\n", port);
	return 0;
}



static void
messageserv (int s, void *v1, void *p OPTIONAL)
{
int theindex;
	
	theindex = (int) v1;

	(void) sockowner (s, Curproc);
	(void) sockmode (s, SOCK_ASCII);
	close_s(Curproc->output);
	close_s(Curproc->input);
	Curproc->output = Curproc->input = s;

	usprintf (s, "%s\n", ports[theindex].message);
        usflush (s);
	kpause (1000);
	close_s (s);
}


#endif

