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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s RENUSER <#oldnick> <newnick>\nRename a user from oldnick to newnick\nOld nickname should be taken from the saved database, and therefor be given as  #oldnick !", BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Rename a user");
  dl->level = 950;
#if 0
  dl->func = m_renuser;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_renuser");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_renuser(char *a)
{
  int i, len;
  char buffer[512];
  char victim[NICKLEN+2],nick_new[NICKLEN+1];
  struct dbaseuser *v;
  struct dbaseuser *d;

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s renameuser [%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(victim,getword(a,&i),NICKLEN+1);
  victim[NICKLEN+1] = '\0';
  if(!strlen(victim)) {
    say_sender("You forgot the first nickname parameter");
    say_sender_( "/msg %s RENUSER <oldnick> <newnick>", BOT_NAME);
    say_sender_( "/msg %s RENUSER <#oldnick> <newnick>", BOT_NAME);
    return;
  }
  strncpy(nick_new,getword(a,&i),NICKLEN);
  nick_new[NICKLEN] = '\0';
  if(!strlen(nick_new)) {
    say_sender("You forgot the new nickname parameter");
    say_sender_( "/msg %s RENUSER <oldnick> <newnick>", BOT_NAME);
    say_sender_( "/msg %s RENUSER <#oldnick> <newnick>", BOT_NAME);
    return;
  }

  if (victim[0]!='#') {
    v=finduserfromnick(victim);
  } else {
    v=finduserfromname(victim+1);
  }
  if(!v) {
    say_sender("Can't find that nickname.");
    return;
  }

  d = finduserfromname(nick_new);
  if(d) {
    say_sender("That nick already exist.");
    return;
  }

  Remove(v->h_elem_nick);
  Free(v->nick);
  len = MIN(strlen(nick_new), NICKLEN);
  v->nick = Malloc(len + 1);
  strncpy(v->nick, nick_new, len);
  v->nick[len] = '\0';
  /*
  strncpy(v->nick, nick_new, NICKLEN);
  v->nick[NICKLEN] = '\0';
  */
  AddElem(dbusers_nick, v->h_elem_nick);

  sprintf(buffer, "'%s' changed to '%s'", victim, nick_new);
  say_sender(buffer);
  say_sender("Done.");
  return;
}
