/*
 *  nwfsinfo.c
 *
 *  Print the info strings of a server, maybe sometime more.
 *
 *  Copyright (C) 1996 by Volker Lendecke
 *
 */

#include <stdio.h>
#include <unistd.h>
#include "ncplib.h"

static char *progname;

static void
usage(void)
{
	fprintf(stderr, "usage: %s [pattern]\n", progname);
}

static void
str_trim_right(char *s, char c)
{
	int len = strlen(s) - 1;

	while ((len > 0) && (s[len] == c))
	{
		s[len] = '\0';
		len -= 1;
	}
}

static void
help(void)
{
        printf("\n");
        printf("usage: %s [options]\n", progname);
        printf("\n"
	       "-h             Print this help text\n"
	       "-S server      Server name to be used\n"
	       "-a             Print Station's addr\n"
	       "\n");
}

int
main(int argc, char **argv)
{
	struct ncp_conn *conn;
	int opt;
	long err;
	struct ncp_file_server_info info;
	struct ncp_bindery_object user;
	time_t login_time;
	int i;
	int print_addr = 0;

	progname = argv[0];

	if ((conn = ncp_initialize(&argc, argv, 1, &err)) == NULL)
	{
		com_err(argv[0], err, "when initializing");
		goto finished;
	}

	while ((opt = getopt(argc, argv, "h?a")) != EOF)
	{
		switch(opt)
		{
		case 'h':
		case '?':
			help();
			goto finished;
		case 'a':
			print_addr = 1;
			break;
		default:
			usage();
			goto finished;
		}
	}

	if (ncp_get_file_server_information(conn, &info) != 0)
	{
		perror("Could not get server information");
		ncp_close(conn);
		return 1;
	}

	if (isatty(1))
	{
		if (print_addr == 0)
		{
			printf("\n%-6s%-21s%-12s\n"
			       "---------------------------------------------"
			       "------\n",
			       "Conn",
			       "User name",
			       "Login time");
		}
		else
		{
			printf("\n%-6s%-21s%-27s%-12s\n"
			       "---------------------------------------------"
			       "---------------------------------\n",
			       "Conn",
			       "User name",
			       "Station Address",
			       "Login time");
		}
	}

	for (i = 1; i <= info.MaximumServiceConnections; i++)
	{
		char name[49];
		name[48] = '\0';
		if (ncp_get_stations_logged_info(conn, i, &user,
						 &login_time) != 0)
		{
			continue;
		}
		memcpy(name, user.object_name, 48);
		str_trim_right(name, ' ');
		printf("%4d: %-20s ", i, name);

		if (print_addr != 0)
		{
			struct sockaddr_ipx addr;
			__u8 conn_type;
			
			memset(&addr, 0, sizeof(addr));
			ncp_get_internet_address(conn, i, &addr, &conn_type);
			ipx_print_saddr(&addr);
			printf(" ");
		}

		printf("%s", ctime(&login_time));
	}

 finished:
	ncp_close(conn);
	return 0;
}
