/*
 * networking.c
 * (C) Peter Salanki 2002
 * This program is copyright, and covered by the Gnu Public License.
 * The Natasha bot.
 * sorcer@linux.se
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <dlfcn.h>
#include "../../settings.h"
#include "../../globals.h"
#include "../../bottypes.h"
#include "networking.h"

pthread_t tailthread;

MODULE_INIT _module_init(MODULE m) {
  strncpy(m->name, NAME, 20);
  strncpy(m->compiledate, __DATE__ " " __TIME__, 30);
  m->version = VERSION;  

  /* Create tail (listener) thread */
  if(pthread_create(&tailthread, NULL, listener, NULL)) printf("Error creating thread for networking tail."); 
}

MODULE_DESTROY _module_destroy(MODULE m) {
  destroylistener = 1;
  close(tailfd);
  close(listenfd);
  /* Join tail (listener) thread */
  if(pthread_join(tailthread, NULL)) printf("Error joining thread for networking tail.");
}


/* Generic functions */
int putsocket (char *text, int fd)
{
  int l, j;
 
  l = strlen (text);
  
  j = write (fd, text, l);
#ifdef DEBUG
  write (1, text, l);
#endif

  if (j != l)
    {
      perror ("write:");
      return 0;
    }
  return 1;
}

int netparse (char *buffer, BOOL forward) {
  
  int i = 0;
  int j = 0;
  char command[64] = "";
  int target;
  char tail[MAX_NETDATA];

  sscanf(buffer, "%i %s", &target, command);

  if((target == 0) || (target == atoi(SID))) {
    
    if(target == 0) {
      /* Forward broadcasts */
      
      if(forward); // Send to head
      else putsocket(buffer, tailfd); 
    }
    
    for (; buffer[i] != '\0' && (buffer[i] != ' '); ++i);
    ++i;
    for (; buffer[i] != '\0' && (buffer[i] != ' '); ++i);
    ++i;

    while ((buffer[i]) && (buffer[i] != '\n')) {
      tail[j] = buffer[i];
      ++j;
      ++i;
    }

    nethandle(command, tail); /* Handle a global command or command to us */

  } else {
    if(forward); // Send to head
    else putsocket(buffer, tailfd);
  }
  return 0;
}

void nethandle(char *command, char *tail) {
  if(strcasecmp(command, "PRIVMSG") == 0) net_privmsg(tail);
  
  else printf("Warning: Unknown command received on servicenet.\n"); 
}

/* Command handlers */
void net_privmsg(char *tail) {
  char msg[512] = "";
  char out[512];
  char target[CHANNELLEN] = "";
  int i = 0;
  int j = 0;
  struct arm *am;

  while (tail[i] != ' ' && tail[i] != '\0' && i < CHANNELLEN) {
    target[j] = tail[i];
    ++i;
    ++j; 
  }
    
  ++i;
  j = 0;
  while (tail[i] != '\0' && j < 512) {
    msg[j] = tail[i];
    ++i;
    ++j; 
  }

  snprintf(out, 512, "PRIVMSG %s :%s\n\r", target, msg);
  
  am = firstarm;
  while (am != NULL)
    {
      if(am->status == 1 && am->id != 1) putserver(out, am);
      am = am->next;
    }
}
