#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAS_SYSLOG
#include <syslog.h>
#endif
#include <sysexits.h>
#include <sys/param.h>
#include "getopt.h"
#include "lutil.h"
#include "xutil.h"
#include "ftn.h"
#include "nodelist.h"
#include "nlindex.h"
#include "config.h"
#include "version.h"
#include "trap.h"


void usage(void)
{
  confusage("<node>\n");
}


int main(int argc, char *argv[])
{
  int c, i, rc;
  faddr *addr = NULL;
  node *nlent;
  char flagbuf[256];


#if defined(HAS_SYSLOG) && defined(CICOLOG)
  logfacility=CICOLOG;
#endif

  setmyname(argv[0]);
  catch(myname);

  while ((c = getopt(argc, argv, "hx:I:")) != -1)
  {
    if (confopt(c,optarg))
    {
      switch (c)
      {
       default:
	usage();
	exit(EX_USAGE);
      }
    }
  }

  if (readconfig())
  {
    fprintf(stderr, "Error getting configuration, aborting\n");
    exit(EX_DATAERR);
  }

  rc = 1;
  if (argv[optind] == NULL)
  {
    usage();
    rc = EX_USAGE;
  }
  else if ((addr = parsefaddr(argv[optind])) == NULL)
  {
    logerr("unrecognizable address \"%s\"", argv[optind]);
    rc = EX_USAGE;
  }

  if (rc == 1)
  {
    nlent = getnlent(addr);
    if (nlent->pflag != NL_DUMMY)
    {
      addr->name=nlent->sysop;
      if (addr->domain == NULL) addr->domain = xstrcpy("fidonet");

      printf("System:    %s\n", nlent->name);
      printf("Sysop:     %s\n", ascinode(addr, 0x7f));
      if (nlent->location)
	printf("Location:  %s\n", nlent->location);
      if (nlent->phone)
	printf("PhoneNo:   %s\n", nlent->phone);
      printf("Speed:     %d\n", nlent->speed);

      /* get nodelist flags */
      flagbuf[0] = 0;
      for (i = 0; fkey[i].flag != 0; i++)
      {
	if ((nlent->flags & fkey[i].flag) == fkey[i].flag)
	{
	  sprintf(flagbuf + strlen(flagbuf), "%s,", fkey[i].key);
	}
      }
      if (strlen(flagbuf))
	flagbuf[strlen(flagbuf) - 1] = 0;
      printf("NL-Flags:  %s\n", flagbuf);

      /* get user nodelist flags */
      flagbuf[0] = 0;
      for (i = 0; nlent->uflags[i]; i++)
      {
	sprintf(flagbuf + strlen(flagbuf), "%s,", nlent->uflags[i]);
      }
      if (strlen(flagbuf))
      {
	flagbuf[strlen(flagbuf) - 1] = 0;
	printf("NL-UFlags: %s\n", flagbuf);
      }

      /* get pflags */
      flagbuf[0] = 0;
      for (i = 0; pkey[i].type != 0; i++)
      {
	if (nlent->pflag == pkey[i].pflag)
	{
	  strcpy(flagbuf, pkey[i].key);
	  break;
	}
      }
      printf("PFlag:     %s\n", flagbuf);

      if (nlent->hub)
	printf("HubSystem: %d\n", nlent->hub);

      rc = 0;
    }
  }

  return rc;
}
