#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "oak.h"

void oak_global_init(oak_global *g) {
  /* set defaults */
  strcpy(g->logfile, "/var/adm/messages");
  g->nukepid=0;
  g->nukeciscopid=0;
  g->ignorehosts=0;
  g->onlyhosts=0;
  g->hostsort=0;
  oak_list_create(&(g->matchlist));
  oak_list_create(&(g->queuelist));
}

char *oak_global_get_logfile(oak_global *g) {
  return(g->logfile);
}

void oak_global_set_logfile(oak_global *g, char *filename) {
  strcpy(g->logfile, filename);
}

oak_queuelist *oak_global_get_queuelist(oak_global *g) {
  return(&(g->queuelist));
}

oak_matchlist *oak_global_get_matchlist(oak_global *g) {
  return(&(g->matchlist));
}

int oak_global_is_nukepid(oak_global *g) {
  return(g->nukepid);
}

void oak_global_set_nukepid(oak_global *g) {
  g->nukepid=1;
}

void oak_global_set_no_nukepid(oak_global *g) {
  g->nukepid=0;
}

int oak_global_is_nukeciscopid(oak_global *g) {
  return(g->nukeciscopid);
}

void oak_global_set_nukeciscopid(oak_global *g) {
  g->nukeciscopid=1;
}

void oak_global_set_no_nukeciscopid(oak_global *g) {
  g->nukeciscopid=0;
}

int oak_global_host_is_ok(oak_global *g, char *host) {
  int i, j;

  /* if there's no filtering then it's ok */
  if (!g->onlyhosts && !g->ignorehosts) return(1);

  /* readconfig is not supposed to allow both onlyhosts and
  ignorehosts to be set.  If it does happen lets just let everything
  though */
  if (g->onlyhosts && g->ignorehosts) return(1);

  /* we're doing one kind of filtering or the other */
  j=oak_list_get_size(&(g->hostlist));
  for (i=0; i<j; i++) {
    if (!strcasecmp(oak_list_get_element(&(g->hostlist), i), host)) {
      if (g->onlyhosts) return(1);
      if (g->ignorehosts) return(0);
    }
  }
  if (g->onlyhosts) return(0);
  if (g->ignorehosts) return(1);
  return(1); /* just for saftey */
}

int oak_global_set_ignorehosts(oak_global *g, char *hosts) {
  /* if an onlyhosts list has been set then return -1, otherwise set
     up the list and return 0 */
  if (g->onlyhosts) return(-1);
  g->ignorehosts=1;
  _oak_global_set_hostlist(g, hosts);
  return(0);
}

int oak_global_set_onlyhosts(oak_global *g, char *hosts) {
  /* if an ignorehosts list has been set then return -1, otherwise set
     up the list and return 0 */
  if (g->ignorehosts) return(-1);
  g->onlyhosts=1;
  _oak_global_set_hostlist(g, hosts);
  return(0);
}

void _oak_global_set_hostlist(oak_global *g, char *hosts) {
  char **foo;
  int n, i;

  oak_list_create(&(g->hostlist));
  foo=argstring_to_argv(hosts, &n);
  for (i=0; i<n; i++) {
    oak_list_append_element(&(g->hostlist), foo[i]);
    if (DEBUG) printf("DEBUG: appending host %s to hostlist.\n", foo[i]);
  }
}
