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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s SETPASS <nickname> <new password> <new password>\nSet some other user's password. The new password MUST be given twice, to check that you didn't mistype it.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Set some other user's password");
  dl->level = 990;
#if 0
  dl->func = m_setpass;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_setpass");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_setpass(char *a)
{
  int i;
  struct dbaseuser *p;
  char victim[NICKLEN+2];
  char password1[PASSLEN+1];
  char password2[PASSLEN+1];

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s setpass [%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 to type the nickname.");
    say_sender_("/msg %s SETPASS <nickname> <password> <password>", BOT_NAME);
    return;
  }
  strncpy(password1,getword(a,&i),PASSLEN);
  password1[PASSLEN] = '\0';
  strncpy(password2,getword(a,&i),PASSLEN);
  password2[PASSLEN] = '\0';
  if(!strlen(password1) || !strlen(password2)) {
    say_sender( "You forgot to type the new password twice.");
    say_sender_( "/msg %s SETPASS <nickname> <password> <password>", BOT_NAME);
    return;
  }
  if (strcmp(password1,password2)!=0) {
    say_sender_("Passwords do not match. (/msg %s HELP SETPASS)", BOT_NAME);
    return;
  }
  if (victim[0]!='#') {
    p=finduserfromnick(victim);
  } else {
    p=finduserfromname(victim+1);
  }
  if(!p) {
    say_sender( "Couldn't find that user in database.");
    return;
  }
  strncpy(p->password, password1, PASSLEN);
  p->password[PASSLEN] = '\0';
  say_sender( "OK, password changed.");
  return;
}
