/*
 * spewemail.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_spewemail(char *a);

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s SPEWEMAIL <*pattern*>\nThis returns a list of all users (from database) which E-mails match the pattern\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Search for an E-mail in database.");
  dl->level = 990;
#if 0
  dl->func = m_spewemail;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_spewemail");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_spewemail(char *a)
{
  struct dbaseuser *u;
  char str[NICKLEN+2];
  ListElem *el;
  int matches = 0;
  int i;
  int nr = 0;
  int email_set = 0;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s spewemail [%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(str,getword(a,&i),NICKLEN+1);
  str[NICKLEN+1] = '\0';
  if(!strlen(str)) {
    say_sender( "You forgot the search pattern.");
    say_sender_( "/msg %s SPEWEMAIL *pattern*", BOT_NAME);
    return;
  }
  el = GetHead(dbuser_list);
  while(el) {
    u = (struct dbaseuser *)el->data;
    if(u->email) {
      if( !match(str, u->email) ) {
	if(++matches >= 1000) {
	  if(matches == 1000)
	    say_sender( "Sorry... there are too many users to show them all.");
	} else {
	  say_sender_("%-15s %s", u->nick, u->email);
	}
      }
      email_set++;
    }
    nr++;
    el = GetSucc(el);
  }
  say_sender_("Found %d matching emails (%d / %d set) (%.2f%%)",
	      matches, email_set, nr, ((float)email_set * 100.0) / ((float)nr));
  return;
}
