/* -TAG:LICENSE-

   This file is under the DigitalSpark Freeware Class License, see the
   file LICENSE for complete licensing information.

                                                         -TAG:LICENSE- */

#define IN_CB
#include <Threading.h>
#include <Strings.h>
#include "tricky.h"

/* Adds a client socket to the client bus

   Returns -1 on error, or it returns the slot number
*/

extern	void	*Authorize( void );
extern	int    	cBusBroadcast( char *data, int size );

int	cBusAdd( int Sock, char *Info )
{
int		i=0;
pthread_t	AuthPID;


/* Find a free slot on the bus */
while ( i <= MAX_CLIENTS )
   {
   if ( Client[i].State == CS_FREE )
      {
      if ( pthread_mutex_trylock(&Client[i].Mutex) == 0 )
         break;
      }
   i++;
   }

/* if there are no more free slots */
if ( i > MAX_CLIENTS )
   {
   /* max number of clients reached */
   shutdown(Sock,2);
   close(Sock);
   return -1;
   }

/* Write information to the bus slot */
cBus_Connected++;
Client[i].Sock = Sock;
Client[i].State = CS_WAITFOR;
//Client[i].Info = malloc(strlen(Info)+1);
//strcpy(Client[i].Info,Info);
pthread_mutex_unlock(&Client[i].Mutex);
pthread_create(&AuthPID, NULL, (void *)Authorize, NULL);

Error(0,"Client(%i) connected",i);
cBusBroadcast("NOTICE AUTH :*** [TrickyIRC] Client added to bus\r\n",0);

return i;
}
