#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/dostags.h>
#include <stdio.h>
#include <string.h>

#include <proto/exec.h>
#include <proto/dos.h>

#include "/include/server.h"


extern struct List ClientsList;
extern UWORD TotalClients;

#define MAXCLIENTS 100

struct TagItem systags[4] = { SYS_Asynch, TRUE, SYS_Input, NULL, SYS_Output, NULL, TAG_END };


BOOL StartClient( struct ClientNode *node )
{
BPTR lock, oldlock;
char path[256], *cp;
BOOL result = FALSE;

if ( lock = Lock( node->cn_ClientProg, ACCESS_READ ) )
	{
	UnLock( lock );
	strcpy( path, node->cn_ClientProg );

	cp = path + strlen( path ) -1;
	while( cp > path && *cp != '/' && *cp != ':' )
		cp--;
	if ( cp > path )
		{
		*cp = 0;
		cp++;
		}
	lock = Lock( path, ACCESS_READ );
	oldlock = CurrentDir( lock );
	if ( SystemTagList( cp, systags ) != -1 )
		result = TRUE;
	CurrentDir( oldlock );
	}
return result;
}


void AddClient( char *newclient, char *newprog, char *newargs )
{
struct ClientNode *node;

if ( node = AllocVec( sizeof(struct ClientNode), MEMF_ANY | MEMF_CLEAR ) )
	{
	strcpy( node->cn_ClientName, newclient );
	strcpy( node->cn_ClientProg, newprog );
	if ( newargs )
		strcpy( node->cn_ClientArgs, newargs );
	node->cn_Node.ln_Name = node->cn_ClientName;
	AddTail( &ClientsList, (struct Node *)node );
	TotalClients++;
	}
}


struct FileInfoBlock fib;

void GetClientNames( char *listname )
{
BPTR handle;
register ULONG size;
register char *ptr, *current, newclient[CLIENTNAME_MAXLENGTH],
              newprog[PROGNAME_MAXLENGTH], newargs[ARGS_MAXLENGTH];
register UBYTE n;

if ( handle = Open( listname, MODE_OLDFILE ) )
	{
	if ( ExamineFH( handle, &fib ) )
		{
		size = fib.fib_Size;
		if ( ptr = AllocVec( (size + 1), MEMF_ANY | MEMF_CLEAR ) )
			{
			Read( handle, ptr, size );

			current = ptr;
			while( *current )
				{
				n = 0;
				while( *current && *current != ':' && n < CLIENTNAME_MAXLENGTH )
					newclient[n++] = *current++;
				newclient[n] = 0;

				while ( *(++current) && *current == ' ' );

				n = 0;
				while ( *current && *current != '\n' && *current != ' ' && n < PROGNAME_MAXLENGTH )
					newprog[n++] = *current++;
				newprog[n] = 0;

				if ( *current++ == '\n' )
					newargs[0] = NULL;
				else
					{
					n = 0;
					while ( *current && *current == ' ' )
						current++;
					while ( *current && *current != '\n' && n < ARGS_MAXLENGTH )
						newargs[n++] = *current++;
					newargs[n] = 0;
					current++;
					}
				if ( newclient[0] && newprog[0] )
					AddClient( newclient, newprog, newargs );
				}
			FreeVec( ptr );
			}
		}
	Close( handle );
	}
}


void DropClientNames( void )
{
struct ClientNode *node;

while ( node = (struct ClientNode *)RemHead( &ClientsList ) )
	{
	FreeVec( node->cn_ClientArgs );
	FreeVec( node );
	}
}
