/*
 * spew.c
 * (C) Christian Magnusson 2000, Email: d1mag@dtek.chalmers.se
 * This program is copyright, and covered by the Gnu Public License.
 * The Q bot.
 */

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "settings.h"
#include "bottypes.h"
#include "globals.h"
#include "dl.h"

void m_spew(char *a);

MODULE_PUBLIC int _init_spew(void *a, void *b)
{
  dl_command_entry_t *dl = a;
  if(!a) return 0;

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s SPEW <*pattern*>\nThis returns a list of all users (logged in) which match the pattern\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Search for a user (currently logged in)");
  dl->level = 950;
#if 0
  dl->func = m_spew;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_spew");
#endif
  return 1;
}

MODULE_PUBLIC int _remove_spew(char *a, char *b)
{
  remove_command("spew");
  return 1;
}

MODULE_PUBLIC void m_spew(char *a)
{
  struct chanmod *c;
  struct activeuser *u;
  char buffer[BIGBUF+1];
  char pattern[MASKLEN+1];
  char *ban_name;
  ListElem *el;
  int matches = 0;
  int i;
  int len, left = BIGBUF;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s spew [%s]\n", db->nick, a);
  } else
    return;
  if(!is_oper()) {
    say_sender("You are not an Oper.");
    log("To: %s Is not an Oper\n", db->nick);
    return;
  }

  i = 0;
  strncpy(pattern,getword(a,&i),MASKLEN);
  pattern[MASKLEN] = '\0';
  if(!strlen(pattern)) {
    say_sender( "You forgot the search pattern.");
    say_sender_( "/msg %s SPEW *pattern*", BOT_NAME);
    return;
  }
  el = GetHead(auser_list);
  while(el) {
    u = (struct activeuser *)el->data;
    ban_name = banstylename(u->nick,u->username, u->hostname);
    if( !match(pattern, u->nick) ||
      	!match(pattern, u->username) ||
      	!match(pattern, u->hostname) ||
	      !match(pattern, u->fullname) ||
	      !match(pattern, ban_name)) {
	    int pos;
      len = sprintf(buffer, "%s!%s@%s (%s)",
        u->nick, u->username, u->hostname, u->fullname);
      say_sender(buffer);
      len = 0;
      left = 400;
      c = u->chanmodes;
      sprintf(buffer,"   on channels:");
      pos=strlen(buffer);
      while(c) {
        len = snprintf(&buffer[pos], left, " %s%s",
            ((c->mode & (1<<('o'-'a'))) ? "@" : ""),
			      c->channel);
        left-=len;
        pos+=len;
        buffer[pos]='\0';
	      if(left < 2) break;
        c = c->next;
      }
      if (left!=400) say_sender(buffer);
      matches++;
      if(matches >= 250) {
      	say_sender("Too many matches... Found more than 250 users");
	      return;
      }
    }
    el = GetSucc(el);
  }
  say_sender_("Found %d user(s)", matches);
  return;
}
