/*
 * trustcheck.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 MIN(x, y) (((x) < (y)) ? (x) : (y))

void m_trustcheck(char *a);

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "Internal function to check for clones. May be used to change the deafault number of allowed clones per host.\n");
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Internal function to check for clones.");
  dl->level = 999;
#if 0
  dl->func = m_trustcheck;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_trustcheck");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_trustcheck(char *a)
{
  int i, nr;
  ListElem *el;
  char host[HOSTLEN+1];
  struct trusted *tr;
  struct activeuser *u;

  i=0;
  strncpy(host, getword(a,&i), HOSTLEN);
  host[HOSTLEN] = '\0';

  if(host[0] == '\0') {
    return;
  }

  if(host[0] == '#') {
    trusted_users = atoi(&host[1]);
    if(trusted_users <= 1) {
      trusted_users = 0;
      wallop("Clone trigger disabled.", trusted_users);
    } else {
      wallop("Clone trigger changed to %d.", trusted_users);
    }
    return;
  }

  if(trusted_users <= 1) {
    return;
  }

  nr = 0;
  el = GetHead(auser_list);
  while(el) {
    u = (struct activeuser *)el->data;
    if(!strcmp(u->hostname, host)) {
      nr++;
    }
    el = GetSucc(el);
  }

  if(nr > trusted_users) {
    el = GetHead(trusted_list);
    while(el) {
      tr = (struct trusted *)el->data;
      if(!strcmp(tr->host, host)) {
	/* host is trusted */
	if(nr > tr->nr_users) {
	  wallop("Host [%s] trusted for %d users. (%d now)",
		 host, tr->nr_users, nr);
	}
	return;
      }
      el = GetSucc(el);
    }
        wallop("[%d]Clones detected from %s", nr, host);
  }
  return;
}
