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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s BADCHANNELDEL *pattern*\n/msg %s BADCHANNELDEL #3\nRemove an illegal channel from the list. It could either be the exact pattern, or a number.\n",
	   BOT_NAME, BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Remove an illegal channel");
  dl->level = 990;
#if 0
  dl->func = m_badchanneldel;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_badchanneldel");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_badchanneldel(char *a)
{
  ListElem *el;
  struct bad_chan *bad_channel;
  int channelnr;
  int i;
  int nr;
  char channel[CHANNELLEN+1];

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s badchanneldel [%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(channel,getword(a,&i),CHANNELLEN);
  channel[CHANNELLEN] = '\0';
  if(!strlen(channel)) {
    say_sender("You forgot the argument.");
    say_sender("/msg %s BADCHANNELDEL *pattern*  (remove matching channel)");
    say_sender("/msg %s BADCHANNELDEL #3   (remove 3rd channel in list)");
    return;
  }

  channelnr = 0;
  if(channel[0] == '#') {
    if((sscanf(channel, "#%d", &channelnr) != 1) || (channelnr<1) || (channelnr>999)) {
      say_sender( "Wrong channel number.");
      return;
    }

    el = GetHead(bad_channel_list);
    nr=0;
    while(el) {
      nr++;
      if(nr >= channelnr) {
	say_sender_( "%s removed.", ((struct bad_chan *)(el->data))->channel);
	Remove(el);
	FreeElem(el);
	return;
      }
      el = GetSucc(el);
    }
    say_sender("Couldn't find that channel in the list");
    return;
  }
  
  el = GetHead(bad_channel_list);
  while(el) {
    bad_channel = ((struct bad_chan *)(el->data));
    if(bad_channel && bad_channel->channel) {
      if(!match(channel, bad_channel->channel)) {
	say_sender_( "%s removed.", ((struct bad_chan *)(el->data))->channel);
	Remove(el);
	FreeElem(el);
	return;
      }
    }
    el = GetSucc(el);
  }
  say_sender( "Couldn't find that channel in the list");
  return;
}
