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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s DEOPALL #channel\nDeop all users on a channel.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Deop all users on a channel.");
  dl->level = 1;
#if 0
  dl->func = m_deopall;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_deopall");
#endif
  return 1;
}

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

void deop_au(struct activeuser *u, char *channel, int server_hack)
{
  if(!u) return;
  if(!channel || !strlen(channel)) return;

  if(server_hack)
    putserver("%c%c M %s -o %s\n\r", yxx[0], yxx[1], channel, u->yxx);
  else
    putserver("%s M %s -o %s\n\r", yxx, channel, u->yxx);
  c_op_set_modes(0, channel, u);
  return;
}

MODULE_PUBLIC void m_deopall(char *a)
{
  int i;
  char channel[CHANNELLEN+1];
  unsigned int slevel;
  struct chanopts *c;
  struct chanmod *cm;
  ListElem *el;
  int oper;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s deopall [%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 DEOPALL #channel", BOT_NAME);
    return;
  }

  oper = is_oper();
  slevel = userlevelonchan_d(sender_au->dbuser, channel);

  if(slevel==0) {
    if(!oper || (sender_au->auth<950)) {
      say_sender( "You are not known on this channel and can't use DEOPALL!");
      return;
    }
  }

  if(!oper && (sender_au->auth<950)) {
    if ((!(slevel & CHAN_MASTER)) && (!(slevel & CHAN_OWNER))) {
      say_sender("You should have +m flag on this channel (and be AUTHED) to use this command!");
      return;
    }
  }

  c = findchannel(channel);
  if(c && c->suspended) { say_sender("Channel is suspended"); return; }

  el = GetHead(auser_list);
  while(el) {
    cm = ((struct activeuser *)el->data)->chanmodes;
    while (cm) {
      if(!strcasecmp(cm->channel, channel)) {
	if(cm->mode & (1<<('o'-'a'))) {
	  cm->mode &= (~0 - (1<<('o'-'a')));
	  deop_au(((struct activeuser *)el->data), channel,
		  ((c && c->bot_joined) ? 0 : 1));
	}
      }
      cm = cm->next;
    }
    el = GetSucc(el);
  }
  say_sender( "Done.");
  return;
}
