/*
 * Citadel/UX "who is logged in" report
 * see copyright.doc for copyright information
 * v1.3
 * 
 * This version should be much more portable than previous versions.  I have
 * tested it under SCO Unix, and Linux.
 */

#include <stdio.h>
#include <fcntl.h>
#include <pwd.h>
#include <ctype.h>
#include "citadel.h"

struct config config;

struct passwd *getpwnam();

center_string(buf,len)
char buf[];
int len; {
	int a;

	while(strlen(buf)<len) {
		strcat(buf," ");
		if (strlen(buf)<len) {
			for (a=len; a>=1; --a) buf[a]=buf[a-1];
			buf[0]=32;
			}
		}
	}

main() {
	int wfile,a;
	FILE *who;
	struct passwd *pwbuf;
	char buf[64];
	char wport[64];
	char wname[64];
	char fname[64];
	char wroom[64];
	struct wtmpsupp wtmpsupp;

	get_config();
	who=(FILE *)popen("who","r");
	printf(" Port              Name                       Room\n");
	printf("------- ------------------------------ --------------------\n");
	while(fgets(buf,64,who)!=NULL) {
		strcpy(wname,buf);
		strcpy(wport,buf);
		for (a=0; a<strlen(wname); ++a) if (wname[a]==32) wname[a]=0;
		while ((!isspace(wport[0]))&&(strlen(wport)>0))
			strcpy(wport,&wport[1]);
		strcpy(wroom,"");
		while (wport[0]==32) strcpy(wport,&wport[1]);
		while (wname[0]==32) strcpy(wname,&wname[1]);
		while(isspace(wname[strlen(wname)-1])) wname[strlen(wname)-1]=0;
		while(isspace(wport[strlen(wport)-1])) wport[strlen(wport)-1]=0;
		for (a=0; a<strlen(wport); ++a) if (wport[a]==32) wport[a]=0;
		if (wname[0]!=0) {
			pwbuf=getpwnam(wname);
			strcpy(fname,pwbuf->pw_gecos);

	wfile=open("wtmpsupp",O_RDONLY);
	do {
		a=read(wfile,&wtmpsupp,sizeof(struct wtmpsupp));
		if (!strcmp(&wtmpsupp.WStty[5],wport)) {
			if ((pwbuf->pw_uid)==BBSUID) 
				strcpy(fname,wtmpsupp.WSname);
			strcpy(wroom,wtmpsupp.WSroom);
			}
		} while((a>0)&&(strcmp(&wtmpsupp.WStty[5],wport)));
		close(wfile);

	center_string(fname,30);
	center_string(wroom,20);
	printf("%-7s %30s %20s\n",wport,fname,wroom);
		}
	}
	pclose(who);
	exit(0);
}
