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

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

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

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

MODULE_PUBLIC void m_welcome(char *a)
{
  int start, i = 0;
  char channel[CHANNELLEN+1];
  char welcome_test[11];
  struct chanopts *c;
  int oper;

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

  strncpy(channel,getword(a,&i),CHANNELLEN);
  channel[CHANNELLEN] = '\0';
  if(!strlen(channel)) {
    say_sender("You forgot the #channel parameter");
    say_sender_("/msg %s WELCOME #channel         (Show welcome message)", BOT_NAME);
    say_sender_("/msg %s WELCOME #channel Hello   (Set welcome message)", BOT_NAME);
    return;
  }
  c = findchannel(channel);
  if(!c) {
    say_sender("No such channel registered!");
    return;
  }
  if(c && c->suspended && !is_oper()) { say_sender("Channel is suspended"); return; }

  oper = is_oper();

  if((oper && (sender_au->auth>=950)) ||
     (userlevelonchan_d(sender_au->dbuser, channel) & (CHAN_MASTER|CHAN_OWNER))) {
    start = i+1;
    strncpy(welcome_test, getword(a,&i), 10);
    welcome_test[10] = '\0';

    if(!strlen(welcome_test)) {
      if(strlen(c->welcome)) {
	say_sender( "Current Welcome message is:");
	say_sender( c->welcome);
      } else {
	say_sender( "No Welcome message is set.");
      }
      say_sender_( "To activate Welcome message:   /msg %s CHANFLAGS #channel +w", BOT_NAME);
      say_sender_( "To deactivate Welcome message: /msg %s CHANFLAGS #channel -w", BOT_NAME);
      return;
    }
    strncpy(c->welcome, &a[start], WELCOMELEN);
    c->welcome[WELCOMELEN] = '\0';
    say_sender("Done.");
  } else {
    say_sender("You don't have +m flag on that channel.");
  }
  return;
}
