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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s EMAIL <user@host.com>\nChange your E-mail. This is used if you have forgotten your password and want to get it by E-mail. It's NOT possible to view other users E-mail addresses.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Change your E-mail");
  dl->level = 1;
#if 0
  dl->func = m_email;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_email");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_email(char *a)
{
  int i, len;
  char email1[EMAILLEN+1];

  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s email [%s]\n", db->nick, a);
  } else {
    say_sender("Couldn't locate you... internal error");
    return;
  }

  /*
  if(sender_au->userid==0) {
    say_sender("You need to AUTH with your old password first.");
    return;
  }
  */
  i=0;
  strncpy(email1,getword(a,&i),EMAILLEN);
  email1[EMAILLEN] = '\0';
  if(!email1[0]) {
    if(!db->email) {
      say_sender("You haven't set any E-mail yet!");
      return;
    }
    say_sender_("Your E-mail is set to: %s", db->email);
    return;
  }
  len = MIN(strlen(email1), EMAILLEN);
  if(len <= 4) {
    say_sender("Email too short");
    return;
  }
  if(strstr(&email1[1], "@") == NULL) {
    say_sender("Email must contain a @");
    return;
  }
  if(email1[len-1] == '@') {
    say_sender("Email must not end with a @");
    return;
  }
  for(i=0; i<len; i++) {
    if(!isalpha(email1[i]) && !isdigit(email1[i])
       && !(email1[i]=='@') && !(email1[i]=='.')
       && !(email1[i]=='_') && !(email1[i]=='-')) {
      say_sender("Email contains invalid characters");
      return;
    }
  }

  
  if(db->email) Free(db->email);
  db->email = Malloc(len + 1);
  strncpy(db->email, email1, len);
  db->email[len] = '\0';
  say_sender("OK, E-mail changed.");
  sqlqlog(QLOG_EMAILSET,sender_au->nick,sender_au->username,sender_au->hostname,"%s %s",db->nick,db->email);
  return;
}
