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

#include "/include/server.h"

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <stdio.h>
#include <string.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, prev_lock, check_lock;
char path[CLIENTNAME_MAXLENGTH], *filename, *pathname;
BOOL success = FALSE;
LONG dos_report;

strcpy( path, node->cn_ClientName );
filename = FilePart( path );
pathname = PathPart( path );
if ( pathname != path )
	*pathname = 0;
if ( lock = Lock( path, ACCESS_READ ) )
	{
	prev_lock = CurrentDir( lock );

	if ( check_lock = Lock( filename, ACCESS_READ ) )
		{
		UnLock( check_lock );
		dos_report =  SystemTagList( filename, systags );
		if ( dos_report != -1 )
			success = TRUE;
		}
	CurrentDir( prev_lock );
	UnLock( lock );
	}
return success;
}


void AddClient( char *newname )
{
struct ClientNode *node;

if ( node = AllocVec( sizeof(struct ClientNode), MEMF_ANY | MEMF_CLEAR ) )
	{
	strcpy( node->cn_ClientName, newname );
	node->cn_Node.ln_Name = FilePart( node->cn_ClientName );
	AddTail( &ClientsList, node );
	TotalClients++;
	}

}


void GetClientNames( char *listname )
{
BPTR handle;
struct FileInfoBlock fib;
register ULONG size;
register char *ptr, *current;
register char newclient[CLIENTNAME_MAXLENGTH];
register UBYTE n;

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

			current = ptr;
			while( current < ( ptr + size ) )
				{
				n = 0;
				while( *current != '\n' && current < ( ptr + size ) )
					newclient[n++] = *current++;
				newclient[n] = 0;
				current++;
				AddClient( newclient );
				}
			FreeVec( ptr );
			}
		}
	Close( handle );
	}
}


void DropClientNames( void )
{
struct ClientNode *node;

while ( node = (struct ClientNode *)RemHead( &ClientsList ) )
	FreeVec( node );
}
