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


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

#define MAXTSCRIPTPORTS 10
struct t_portsused {
	int	port;
	int	sock;
	uint32	address;
	char	*script;
};
static struct t_portsused ports[MAXTSCRIPTPORTS];

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



/* Start up the tscript service */
int
tscript1 (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! TSCRIPT server NOT started on port %d!\n",
				argv[3], port);
			return 0;
		}
	}

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

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

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

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



int
tscript0 (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! TSCRIPT server NOT stopped on port %d!\n",
				argv[2], port);
			return 0;
		}
	}
	for (k = 0; k < MAXTSCRIPTPORTS; k++) {
		if (ports[k].port == port && ports[k].address == address)	{
			ports[k].port = 0;
			free (ports[k].script);
			ports[k].script = NULLCHAR;
			return (deleteserver (&ports[k].sock));
		}
	}
	tprintf ("Sorry, but no TSCRIPT server was found on port #%d for that address!\n", port);
	return 0;
}



static void
tscriptserv (int s, void *v1, void *p OPTIONAL)
{
int theindex;
char *args[2];
	
	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;

	args[1] = ports[theindex].script;
	(void) doscript (2, args, (void *) -1);

        usflush (s);
	kpause (1000);
	close_s (s);
}


#endif


