#include "xzul.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <com_err.h>
#include <strings.h>
#include <errno.h>
#include <sys/types.h>
#include <krb_err.h>

extern int __Zephyr_port;

int zfct(Code_t code, char *msg)
{
  if (code != ZERR_NONE)
  {
    if ((code != ZERR_HMDEAD) && (code != ZERR_SERVNAK))
      fprintf(stderr, "%s: %s %s\n", progName, error_message(code), msg);
    return(0);
  }
  return(1);
}

void zephyr_init(void)
{
  initialize_krb_error_table();
  zfct(ZInitialize(), "while initializing");
  zfct(ZOpenPort(NULL), "while opening port");
}

void zephyr_cleanup(void)
{
  zfct(ZCancelSubscriptions(0),"while cancelling subscriptions");
}

char *zephyr_fixuser(char *name)
{
  char *kname, *realm;
  if (! strchr(name, '@'))
  {
    realm = ZGetRealm();
    if (!(kname = (char*) malloc (strlen(name) + strlen(realm) + 2)))
      return(0);
    strcpy(kname, name);
    strcat(kname, "@");
    strcat(kname, realm);
    return(kname);
  }
  return(mystrdup(name));
}

#if 1
void zephyr_locate(char *kname)
{
  static ZNotice_t notice;
  static int set = 0;

  if (!set)
  {
    memset((char*)&notice, 0, sizeof(notice));
    notice.z_kind = UNSAFE; /*UNACKED;*/
    notice.z_port = __Zephyr_port;
    notice.z_class = LOCATE_CLASS;
    notice.z_opcode = LOCATE_LOCATE;
    notice.z_sender = 0;
    notice.z_recipient = "";
    notice.z_default_format = "";
    notice.z_message_len = 0;
    set = 1;
  }
  notice.z_class_inst = kname; 
  zfct(ZSendNotice(&notice, ZAUTH), "while requesting locations");
}
#else
void zephyr_locate(char *kname)
{
  ZAsyncLocateData_t ald;

  if (zfct(ZRequestLocations(kname, &ald, UNACKED, ZAUTH),
	   "while requesting locations"))
    ZFreeALD(&ald);
}
#endif

/*
void zephyr_sub(char *kname)
{
  ZSubscription_t sub;

  sub.zsub_recipient = "";
  sub.zsub_class = LOGIN_CLASS;
  sub.zsub_classinst = kname;

  zfct(ZSubscribeToSansDefaults(&sub, 1, 0), "while subscribing");
}
*/

void read_file(void)
{
  FILE *fp;
  char buf[1024], buf2[1024], buf3[1024], *ptr;
  User_t *user, *puser;
  Location_t *loc, *ploc;

  if (gAnyoneFile[0] == '~' && gAnyoneFile[1] == '/')
  {
    if (!(ptr = getenv("HOME")))
    {
      fprintf(stderr, "%s: HOME environment variable not set\n", progName);
      exit(1);
    }
    strcpy(buf, ptr);
    strcat(buf, gAnyoneFile+1);
    ptr = buf;
  }
  else
    ptr = gAnyoneFile;

  if (!(fp = fopen(ptr, "r")))
  {
    fprintf(stderr,"%s: %s opening %s\n", progName, error_message(errno), ptr);
    exit(1);
  }

  user = gUserList.first;
  while (user)
  {
    free(user->kname);
    loc = user->locs;
    while (loc)
    {
      free(loc->host);
      free(loc->time);
      free(loc->tty);
      ploc = loc->next;
      free(loc);
      loc = ploc;
    }
    puser = user->next;
    free(user);
    user = puser;
  }
  gUserList.first = gUserList.last = 0;
  buf2[0] = buf3[0] = 0;
  while (fgets(buf, 1024, fp))
  {
    ptr = buf + strlen(buf) - 1;
    if (*ptr == '\n')
      *ptr = 0;
    ptr = buf;
    if (ptr[0] == '#' && ptr[1] == '#')
    {
      ptr += 2;
      if (*ptr == '#')
      {
	buf2[0] = 0;
	continue;
      }
      while (*ptr && (*ptr == ' ' || *ptr == '\t'))
	ptr++;
      if (!*ptr)
	buf2[0] = 0;
      else
	strcpy(buf2, ptr);
      continue;
    }
    if (!strncmp(ptr, "#alias", 6))
    {
      ptr += 6;
      while (*ptr && (*ptr == ' ' || *ptr == '\t'))
        ptr++;
      if (!*ptr)
        buf3[0] = 0;
      else
        strcpy(buf3, ptr);
      continue;
    }
    while (*ptr && *ptr != ' ' && *ptr != '\t' && *ptr != '#')
      ptr++;
    *ptr = 0;
    if (buf[0] == 0)
    {
      buf2[0] = buf3[0] = 0;
      continue;
    }

    if (!(user = (User_t *)malloc(sizeof(User_t))))
    {
      fprintf(stderr, "%s: %s adding user\n", progName, error_message(errno));
      buf2[0] = buf3[0] = 0;
      continue;
    }
    if (!(user->name = mystrdup(buf3[0] ? buf3 : buf)))
    {
      free(user);
      fprintf(stderr, "%s: %s adding user\n", progName, error_message(errno));
      buf2[0] = buf3[0] = 0;
      continue;
    }
    user->kname = zephyr_fixuser(buf);
    if (buf2[0])
      user->desc = mystrdup(buf2);
    else if (buf3[0])
      user->desc = mystrdup(buf);
    else
      user->desc = 0;
    buf2[0] = buf3[0] = 0;
    user->next = 0;
    user->len = strlen(user->name);
    user->locs = 0;
    if (gUserList.first)
      gUserList.last->next = user;
    else
      gUserList.first = user;
    gUserList.last = user;
  }
  fclose(fp);
}

void resub(void)
{
  ZSubscription_t subs[500];
  User_t *user;
  int i = 0;

  user = gUserList.first;
  while (user)
  {
    subs[i].zsub_recipient = "";
    subs[i].zsub_class = LOGIN_CLASS;
    subs[i].zsub_classinst = user->kname;
    i++;
    if (i == 500)
    {
      zfct(ZSubscribeToSansDefaults(subs, i, 0), "while subscribing");
      i = 0;
    }
    user = user->next;
  }
  if (i)
    zfct(ZSubscribeToSansDefaults(subs, i, 0), "while subscribing");
}

User_t *recheck(User_t *first)
{
  static int bnum = 500;
  int i;

  for (i = 0; i < bnum && first; i++)
  {
    zephyr_locate(first->kname);
    first = first->next;
  }
  gRecheckTime = time(0) + gTimeBetChecks;
  return first;
}

void add_user_loc(char *kname, char *host, char *ttime, char *tty)
{
  User_t *user;
  Location_t *loc;

  user = gUserList.first;
  while (user)
  {
    if (!strcmp(user->kname, kname))
    {
      loc = user->locs;
      while (loc)
      {
	if (!strcmp(host, loc->host) && !strcmp(tty, loc->tty))
	{
	  free(loc->host);
	  free(loc->time);
	  free(loc->tty);
	  loc->host = host;
	  loc->time = ttime;
	  loc->tty = tty;
	  loc->textWidth = 0;
	  loc->valid = 0;
	  if (loc->status == eLogout)
	    loc->status = eNormal;
	  break;
	}
	loc = loc->next;
      }
      if (!loc)
      {
	loc = (Location_t*) malloc(sizeof(Location_t));
	loc->host = host;
	loc->time = ttime;
	loc->tty = tty;
	loc->textWidth = 0;
	loc->valid = 0;
	loc->when = time(0) + gColorTTL;
	loc->status = eLogin;
	loc->next = user->locs;
	user->locs = loc;
      }
      queue_fix_colors();
      break;
    }
    user = user->next;
  }
  free(kname);
}

void del_user_loc(char *kname, char *host, char *ttime, char *tty)
{
  User_t *user;
  Location_t *loc, *ploc;

  user = gUserList.first;
  while(user)
  {
    ploc = 0;
    loc = user->locs;
    while (loc)
    {
      if (!strcmp(user->kname, kname) &&
	  !strcmp(loc->host, host) &&
	  !strcmp(loc->tty, tty))
      {
	loc->valid = 0;
	loc->when = time(0) + gColorTTL;
	loc->status = eLogout;
	queue_fix_colors();
	break;
      }
      ploc = loc;
      loc = loc->next;
    }
    user = user->next;
  }
  free(host);
  free(ttime);
  free(tty);
  free(kname);
}

void del_all_user_loc(char *kname)
{
  User_t *user;
  Location_t *loc;

  user = gUserList.first;
  while(user)
  {
    if (!strcmp(user->kname, kname))
    {
      loc = user->locs;
      while (loc)
      {
	loc->valid = 0;
	loc->when = time(0) + gColorTTL;
	loc->status = eLogout;
	queue_fix_colors();
	loc = loc->next;
      }
      break;
    }
    user = user->next;
  }
  free(kname);
}
