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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s KEY #channel key\nSet a key on a channel. This must be combined with \"/msg %s CHANFLAGS #channel +k\" to keep the key permanent.\n", BOT_NAME, BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Set a key on a channel.");
  dl->level = 1;
#if 0
  dl->func = m_key;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_key");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_key(char *a)
{
  int i;
  char tmp[CHANNELLEN+KEYLEN+80];
  char key[KEYLEN+1];
  char channel[CHANNELLEN+1];
  unsigned int slevel;
  struct chanopts *c;
  int oper;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s key [%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 KEY #channel         - View current key", BOT_NAME);
    say_sender_( "/msg %s KEY #channel key     - Set a new key", 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 KEY!");
      return;
    }
  }

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

  c = findchannel(channel);
  if(!c) {
    say_sender( "Couldn't find channel");
    return;
  }
  if(c->suspended) { say_sender("Channel is suspended"); return; }

  strncpy(key,getword(a,&i),KEYLEN);
  key[KEYLEN] = '\0';
  if(!strlen(key)) {
    sprintf(tmp, "Current key at %s is: %s", c->channel, c->key);
    say_sender( tmp);
    return;
  }
  addkey_ch(c, key, 1);
  say_sender( "Done.");
  return;
}
