/*
 * config.c: dealing configuration files
 *
 * Copyright(c) 1997,1998 - All Rights Reserved
 *
 * See the COPYRIGHT file.
 */

#ifndef lint
static char rcsid[] = "@(#)$Id: config.c,v 1.9 1998/05/25 15:56:58 kalt Exp $";
#endif

#include "os.h"

#include "struct.h"
#include "server.h"
#include "window.h"

extern int cmd_option(char *);
extern int cmd_alias(char *);

char cfgdir[255] = "";

static char fname[255], buf[160];

static void
cfg_inits()
{
  FILE *s;
  int ln = 0;

  strcpy(fname, cfgdir);
  strcat(fname, "server");
  if (s = fopen(fname, "r"))
    {
      char *name, *port, *pass, *uname;
      struct server_ *stmp = NULL;

      while (!feof(s))
	{
	  if (fgets(buf, 160, s) == NULL)
	      break;
	  ln += 1;
	  if (buf[0] == '#')
	      continue;
	  if (buf[0] == '\t')
	    {
	      if (stmp)
		  stmp->rname = strdup(buf+1);
	      else
		  vsic_slog(LOG_CLIENT, "Unable to parse line %d of %s", ln,
			    fname);
	      continue;
	    }
	  if ((name = strtok(buf, " \t\n")) == NULL
	      || (name = strtok(NULL, " \t\n")) == NULL)
	    {
	      vsic_slog(LOG_CLIENT, "Unable to parse line %d of %s", ln,fname);
	      continue;
	    }
	  if ((port = strtok(NULL, " \t\n")) == NULL || atoi(port) == 0)
	    {
	      vsic_slog(LOG_CLIENT, "Invalid port line %d of %s", ln, fname);
	      continue;
	    }
	  pass = strtok(NULL, " \t\n");
	  if (uname = index(buf, '!'))
	      *uname++ = '\0';
	  stmp = sic_server(buf, name, (port) ? atoi(port) : 6667, pass);
	  if (uname)
	      stmp->uname = strdup(uname);
	}
      fclose(s);
    }
}

static void
cfg_inita()
{
  FILE *s;
  int ln = 0;

  strcpy(fname, cfgdir);
  strcat(fname, "alias");
  if (s = fopen(fname, "r"))
    {
      char *j;

      while (!feof(s))
	{
	  if (fgets(buf, 512, s) == NULL)
	      break;
	  ln += 1;
	  if (buf[0] == '#')
	      continue;
	  j = index(buf, '\n');
	  if (index(buf, ' ') == NULL || j == NULL)
	    {
	      vsic_slog(LOG_CLIENT, "Unable to parse line %d of %s", ln,fname);
	      continue;
	    }
	  *j = '\0';
	  cmd_alias(buf);
	}
      fclose(s);
    }
}

void
cfg_init()
{
  char *env;

  if (env = getenv("SICDIR"))
      strcpy(cfgdir, env);
  else
      if (env = getenv("HOME"))
	{
	  strcpy(cfgdir, env);
	  strcat(cfgdir, "/.sic/");
	}
  if (*cfgdir)
    {
      cfg_inits();
      cfg_inita();
    }
}

void
cfg_read(name)
  char *name;
{
  FILE *s;

  strcpy(fname, cfgdir);
  strcat(fname, name);
  if (s = fopen(fname, "r"))
    {
      if (strcmp("top", name))
	  vsic_slog(LOG_CLIENT, "--- Reading options from `%s'.", name);
      while (!feof(s))
	{
	  if (fgets(buf, 160, s) == NULL)
	      break;
	  if (buf[0] == '#')
	      continue;
	  buf[strlen(buf) - 1] = '\0';
	  cmd_option(buf);
	}
      fclose(s);
    }
}
