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

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

  snprintf(dl->help, MAX_COMMAND_HELP_LEN,
	   "/msg %s UNGLINE <user@host>\n/msg %s UNGLINE #1\nRemove a G-line from a host. You can type the exact user@host or corresponding number from GLIST to specify the G-line to remove.\n", BOT_NAME, BOT_NAME);
  snprintf(dl->summary, MAX_COMMAND_SUMMARY_LEN,
	   "Remove a G-line from a host");
  dl->level = 950;
#if 0
  dl->func = m_ungline;
#else
  dl->func = (void (*)(char*)) DL_sym(dl->val, "m_ungline");
#endif
  return 1;
}

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

MODULE_PUBLIC void m_ungline(char *a)
{
  char gline[256];
  char tmp[256];
  struct gline *gp;
  int gnr;
  int nr, i;
  ListElem *el;
  struct dbaseuser *db;
  db = sender_au->dbuser;
  if(db) {
    log("From: %s ungline [%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(gline, getword(a,&i), GLINELEN);
  gline[GLINELEN] = '\0';
  if(strlen(gline) < 2) {
    say_sender( "You forgot to specify which G-line to remove.");
    say_sender_( "/msg %s UNGLINE user@host", BOT_NAME);
    say_sender_( "/msg %s UNGLINE #1", BOT_NAME);
    return;
  }

  if(gline[0] == '#') {
    gnr = atoi(&gline[1]);
    /*
    if(gnr <= 0) {
      say_sender("Invalid number specified.");
      return;
    }
    */
  } else {
    gnr = 0;
  }

  el = GetHead(gline_list);
  nr = 0;
  while(el) {
    gp = (struct gline *)(el->data);
    nr++;
    if(!strcasecmp(gp->gline, gline)) {
      break;
    }
    if(gnr && (gnr == nr)) {
      break;
    }
    el = GetSucc(el);
  }
  
  if(!el) {
    say_sender("G-line not found. List them with GLIST.");
    return;
  }

  putserver("%c%c GL * -%s\n\r", yxx[0], yxx[1], gp->gline);

  sprintf(tmp, "GLINE %s removed by %s\n", gp->gline, sender_au->dbuser->nick);
  log(tmp);
  wallop(tmp);

  gline_del(gp->gline);
  return;
}
