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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s UNGLINEMASK <*pattern*>\nUngline many hosts matching a pattern.\n", BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Ungline many hosts matching a pattern");
  dl->level = 950;
#if 0
  dl->func = m_unglinemask;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_unglinemask");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_unglinemask(char *a)
{
  int i;
  struct dbaseuser *db;
  struct gline *gp;
  char pattern[101];
  ListElem *el;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s unglinemask [%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), 100);
  pattern[100] = '\0';
  if(!strlen(pattern)) {
    say_sender("You forgot the pattern.");
    say_sender_("/msg %s UNGLINEMASK <*pattern*>", BOT_NAME);
    return;
  }

  el = GetHead(gline_list);
  i = 0;
  while(el) {
    gp = (struct gline *)(el->data);
    if(match(pattern, gp->gline) != 0) {
      el = GetSucc(el);
      continue;
    }
    el = GetSucc(el);
    i++;
  }
  
  if(i > 30) {
    say_sender_("You tried to remove too many G-lines. (%d)", i);
    wallop("%s (%s) tried to remove %d G-lines (%s)",
	     sender_au->nick, sender_au->dbuser->nick, i, pattern);
    return;
  }
  
  el = GetHead(gline_list);
  while(el) {
    gp = (struct gline *)(el->data);
    if(match(pattern, gp->gline) != 0) {
      el = GetSucc(el);
      continue;
    }
    el = GetSucc(el);
    putserver("%c%c GL * -%s\n\r", yxx[0], yxx[1], gp->gline);
    gline_del(gp->gline);
  }

  if(i == 0) {
    say_sender("No G-lines found");
  } else {
    wallop("%d G-lines removed by %s (%s) (%s)",
	   i, sender_au->nick, db->nick, pattern);
  }
  return;
}
