/*
 * authhistory.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"

#define UNKNOWN_OWNER "\02???\02"

void m_authhistory(char *a);

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s AUTHHISTORY <channel>\nThis will show a history list with authed users on the actual channel. Could be used to trace stolen passwords etc.\n"
	   , BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Show history with authed users.");
  dl->level = 1;
#if 0
  dl->func = m_authhistory;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_authhistory");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_authhistory(char *a)
{
  int i, pos;
  char tmp[200];
  struct chanopts *c;
  char channel[CHANNELLEN+1];

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

  i=0;
  strncpy(channel,getword(a,&i),CHANNELLEN);
  channel[CHANNELLEN] = '\0';
  if(!strlen(channel)) {
    say_sender("You forgot to type the channel");
    say_sender_("/msg %s AUTHHISTORY #channel", BOT_NAME);
    return;
  }
  
  i = userlevelonchan_d(sender_au->dbuser, channel);
  if((i & (CHAN_OPER | CHAN_MASTER | CHAN_OWNER)) || is_oper()) { 
    c = findchannel(channel);
    if(c) {
      if(c->suspended && !is_oper()) { say_sender("Channel is suspended"); return; }

      /* should never fail */
      sprintf(tmp, "%-16s %-16s on channel %s", "Nick authed as", "User", c->channel);
      say_sender( tmp);
      for(i=0 ; i<AUTH_HISTORY_LEN; i++) {
	pos = (c->auth_history_pos + i) % AUTH_HISTORY_LEN;
	if(c->auth_history_userid[pos] > 0) {
	  db = finduserfromid(c->auth_history_userid[pos]);
	  if(db) {
	    sprintf(tmp, "%-16s %-16s", c->auth_history_nick[pos], db->nick);
	    say_sender( tmp);
	  } else {
	    sprintf(tmp, "%-16s %-16s", c->auth_history_nick[pos], UNKNOWN_OWNER);
	    say_sender( tmp);
	  }
	}
      }
    } 
    say_sender("Done.");
  } else {
    say_sender("You don't have +o flag on that channel.");
  }
  return;
}

