/* Copyright (c) 1996, 1997, 1998 Thorsten Kukuk
   Author: Thorsten Kukuk <kukuk@vt.uni-paderborn.de>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define _GNU_SOURCE

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#else
#include "lib/compat/getopt.h"
#endif
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <libintl.h>
#include <rpcsvc/nis.h>

#ifndef _
#define _(String) gettext (String)
#endif

static int raw_binary = 0;

static int
print_obj (const_nis_name name __attribute__ ((unused)),
	   const nis_object *obj, const void *udata __attribute__ ((unused)))
{
  nis_print_object (obj);

  return 0;
}

static int
print_line (const_nis_name name __attribute__ ((unused)),
	    const nis_object *obj, const void *udata)
{
  const char *separator = udata;
  u_int j;

  for (j = 0; j < obj->EN_data.en_cols.en_cols_len; ++j)
    {
      if (ENTRY_VAL (obj, j) != NULL)
	{
	  if ((obj->EN_data.en_cols.en_cols_val->ec_flags & EN_BINARY)
	      && !raw_binary)
	    fputs (_("*BINARY*"), stdout);
	  else
	    {
	      fprintf (stdout, "%.*s", (int)ENTRY_LEN (obj,j),
		       ENTRY_VAL (obj, j));
	    }
	}
      if (j + 1 < obj->EN_data.en_cols.en_cols_len)
	fputc (*separator, stdout);
    }
  fputs ("\n", stdout);
  return 0;
}

/* Print the version information.  */
static inline void
print_version (void)
{
  fprintf (stdout, "niscat (%s) %s\n", PACKAGE, VERSION);
  fprintf (stdout, gettext ("\
Copyright (C) %s Thorsten Kukuk.\n\
This is free software; see the source for copying conditions.  There is NO\n\
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
"), "1998");
  /* fprintf (stdout, _("Written by %s.\n"), "Thorsten Kukuk"); */
}

static inline void
print_usage (void)
{
  fputs (_("Usage: niscat [ -AhLMv ] [-s sep] tablename ...\n"), stdout);
  fputs (_("       niscat [ -ALMP ] -o name ...\n"), stdout);
}

static void
print_help (void)
{
  print_usage ();
  fputs (_("niscat - dump NIS+ tables and objects\n\n"),
         stdout);

  fputs (_("  -A             Use ALL_RESULTS flag for lookups\n"), stdout);
  fputs (_("  -L             Follow links\n"), stdout);
  fputs (_("  -M             Query master server only\n"), stdout);
  fputs (_("  -P             Follow concatenation path\n"), stdout);
  fputs (_("  -h             Print names of columns\n"), stdout);
  fputs (_("  -o             Display internal representation of object\n"),
	 stdout);
  fputs (_("  -s sep         Use \"sep\" to separate the table columns\n"),
	 stdout);
  fputs (_("  -v             Display binary data directly\n"), stdout);
  fputs (_("  --help         Give this help list\n"), stdout);
  fputs (_("  --usage        Give a short usage message\n"), stdout);
  fputs (_("  --version      Print program version\n"), stdout);
}

static inline void
print_error (void)
{
  const char *program = "niscat";

  fprintf (stderr,
           _("Try `%s --help' or `%s --usage' for more information.\n"),
           program, program);
}

int
main (int argc, char *argv[])
{
  nis_result *res = NULL;
  char separator = '\t';
  int display_header = 0;
  int print_object = 0;
  int new_sep = 0;
  int flags = EXPAND_NAME;
  int i, result = 0;

  setlocale (LC_MESSAGES, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  while (1)
    {
      int c;
      int option_index = 0;
      static struct option long_options[] =
      {
        {"version", no_argument, NULL, '\255'},
        {"usage", no_argument, NULL, '\254'},
        {"help", no_argument, NULL, '\253'},
	{NULL, 0, NULL, '\0'}
      };

      c = getopt_long (argc, argv, "ALMPhos:v", long_options, &option_index);
      if (c == (-1))
	break;
      switch (c)
	{
	case 'o':
	  if (display_header)
	    {
	      fputs (_("You could not use -h and -o !\n"), stderr);
	      print_error ();
	      return 1;
	    }
	  if (new_sep)
	    {
	      fputs (_("You could not use -s and -o !\n"), stderr);
	      print_error ();
	      return 1;
	    }
	  print_object = 1;
	  break;
	case 'h':
	  if (print_object)
	    {
	      fputs (_("You could not use -h and -o !\n"), stderr);
	      print_error ();
	      return 1;
	    }
	  display_header = 1;
	  break;
	case 's':
	  if (print_object)
	    {
	      fputs (_("You could not use -s and -o !\n"), stderr);
	      print_error ();
	      return 1;
	    }
	  new_sep = 1;
	  separator = optarg[0];
	  break;
	case 'A':
	  flags |= ALL_RESULTS;
	case 'L':
	  flags |= FOLLOW_LINKS;
	  break;
	case 'P':
	  flags |= FOLLOW_PATH;
	  break;
	case 'M':
	  flags |= MASTER_ONLY;
	  break;
	case 'v':
	  ++raw_binary;
	  break;
        case '\253':
          print_help ();
          return 0;
        case '\255':
          print_version ();
          return 0;
        case '\254':
          print_usage ();
          return 0;
        default:
          print_error ();
          return 1;
	}
    }

  argc -= optind;
  argv += optind;

  if (argc < 1)
    {
      fputs (_("niscat: Not enough parameters\n"), stderr);
      print_error ();
      return 1;
    }

  for (i = 0; i < argc; ++i)
    {
      /* We could have an indexd name. It is allowed for -o, but
	 forbidden without. But who cares ? We allow it, too.
         At first we need the tablename. */
      char *tablename = strchr (argv[i], ']');

      if (tablename != NULL)
	tablename += 2;
      else
	tablename = argv[i];

      result = 0;
      res = nis_lookup (tablename, flags);

      if (res == NULL ||
	  (res->status != NIS_SUCCESS && res->status != NIS_S_SUCCESS))
	{
	  if (res == NULL)
	    {
	      fputs (_("Out of memory!\n"), stderr);
	      return 1;
	    }
	  else
	    nis_perror (res->status, tablename);
	  nis_freeresult (res);
	  result = 1;
	  continue;
	}

      /* If we have an TABLE_OBJ and don't print the object structure, get
	 the table contents. */
      if (__type_of (NIS_RES_OBJECT (res)) == NIS_TABLE_OBJ &&
	  (!print_object || argv[i][0] == '['))
	{
	  char *buf = alloca (strlen (argv[i]) + 5);

	  if (buf == NULL)
	    {
	      fputs (_("Out of memory!\n"), stderr);
	      return 1;
	    }

	  if (!new_sep && !print_object)
	    {
	      /* Get the separator character */
	      separator = NIS_RES_OBJECT (res)->TA_data.ta_sep;
	    }
	  /* Should we print the header line with the name of the columns ? */
	  if (display_header && !print_object)
	    {
	      unsigned int j;

	      fputs ("# ", stdout);
	      for (j = 0;
		   j < NIS_RES_OBJECT (res)->TA_data.ta_cols.ta_cols_len; j++)
		{
		  fputs (NIS_RES_OBJECT (res)->TA_data.ta_cols.ta_cols_val[j].tc_name, stdout);
		  if (j == NIS_RES_OBJECT (res)->TA_data.ta_cols.ta_cols_len - 1)
		    fputs ("\n", stdout);
		  else
		    fputc (separator, stdout);
		}
	    }

	  /* Get the contents of the table */
	  if (argv[i][0] == '[')	/* Indexed names! */
	    strcpy (buf, argv[i]);
	  else
	    sprintf (buf, "[],%s", argv[i]);

	  /* Now we try to get the contents of the table */
	  if (print_object)
	    res = nis_list (buf, flags, print_obj, NULL);
	  else
	    res = nis_list (buf, flags, print_line, (void *)&separator);
	  if (res == NULL ||
	      (res->status != NIS_SUCCESS && res->status != NIS_CBRESULTS))
	    {
	      if (res == NULL)
		fputs (_("Out of memory!\n"), stderr);
	      else
		{
		  if (res->status == NIS_PARTIAL)
		    return 0;
		  nis_perror (res->status, argv[i]);
		}
	      nis_freeresult (res);
	      result = 1;
	      continue;
	    }
	}
      else
	if (!print_object)
	  /* This couldn't be a TABLE object, so we must print the
	     object structure */
	  {
	    fprintf (stderr, _("%s is not a table!\n"), argv[0]);
	    nis_freeresult (res);
	    result = 1;
	    continue;
	  }
	else
	  {
	    nis_print_object (NIS_RES_OBJECT (res));
	    nis_freeresult (res);
	  }
    }
  return result;
}
