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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s NEWPASS <new password> <new password>\nChange your password. Your new password MUST be given twice, to check that you didn't mistype it.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Change your password");
  dl->level = 1;
#if 0
  dl->func = m_newpass;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_newpass");
#endif
  return 1;
}

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

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

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

  if(sender_au->userid==0) {
    say_sender("You need to AUTH with your old password first.");
    return;
  }
  i=0;
  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 NEWPASS secret secret", BOT_NAME);
    return;
  }
  if (strcmp(password1,password2)!=0) {
    say_sender_("Passwords do not match. (/msg %s HELP NEWPASS)", BOT_NAME);
    return;
  }
  /*  p = finduserfromid(sender_au->userid); */
  p = sender_au->dbuser;
  if(!p) {
    say_sender("Error... Couldn't find you in database during NEWPASS.");
    return;
  }
  strncpy(p->password,password1,PASSLEN);
  p->password[PASSLEN] = '\0';
  say_sender("OK, password changed.");
  sqlqlog(QLOG_PASSCHG,sender_au->nick,sender_au->username,sender_au->hostname,"%s %s",p->nick,(p->globalauth>=100) ? "[hidden because authlev is >=100]" : p->password);
  return;
}
