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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s CLEARCHAN #channel\nClear all modes on a channel. Could be used if someone has set a key/invite only.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Clear all modes on a channel.");
  dl->level = 1;
#if 0
  dl->func = m_clearchan;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_clearchan");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_clearchan(char *a)
{
  int i;
  struct chanopts *c;
  char channel[CHANNELLEN+1];
  int slevel, oper;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s clearchan [%s]\n", db->nick, a);
  } else
    return;

  i = 0;
  strncpy(channel,getword(a,&i),CHANNELLEN);
  channel[CHANNELLEN] = '\0';
  if(!strlen(channel)) {
    say_sender("You forgot the channel parameter");
    say_sender_( "/msg %s CLEARCHAN #channel", BOT_NAME);
    return;
  }
  oper = is_oper();
  slevel = userlevelonchan_d(sender_au->dbuser, channel);
  /* Check to see if they have a high enough level to clear the chan */
  if(slevel==0) {
    if(!oper || (sender_au->auth<950)) {
      say_sender( "You don't have enough access to clear the channel.");
      return;
    }
  }
  if(!oper && (sender_au->auth<950)) {
    if ((!(slevel & CHAN_MASTER)) &&
	(!(slevel & CHAN_OWNER))  &&
	(!(slevel & CHAN_OPER))) {
      say_sender("You should have the +o flag to clear the channel.");
      return;
    }
  }

#if 1
  c = findchannel(channel);
  if(c) {
    if(c->suspended) {
      say_sender("Channel is suspended");
    } else {
      clear_chanmodes(c, 1);
    }
  } else {
    /* in case Q isn't in the channel make a server hack. */
    if(oper && (sender_au->auth>=950)) {
      putserver("%c%c M %s +nt-sipmkl\n\r", yxx[0], yxx[1], channel);
    }
  }
#else
  putserver("%s M %s\n\r", yxx, channel);
#endif
  say_sender( "Done.");
  return;
}
