/*
** CNet Who Daemon Service
** by Kelly Cochran
** Last updated: Sat Sep 20 11:29:11 1997
*/

#include <stdio.h>
#include <stdlib.h>
#include <clib/netlib_protos.h>

#define CYN "[0;36;40m"
#define PUR "[0;35;40m"
#define WHT "[0;37;40m"

struct MainPort *myp       = NULL;
struct Library  *CNet4Base = NULL;

const char *version = "\0$VER: CNet-Who-inetd 3.1 "__AMIGADATE__;

void do_head(void)
{
   int i;
   int len;
   char buffer[90];

   sprintf(buffer, "Who's online %s", myp->gc.MySystemName);
   len = strlen(buffer);

   for (i=0; i < (80-len)/2;i++)
   {
      printf(" ");
   }

   printf(WHT);
   printf(buffer);
   printf("\n\n");
}   

void do_foot(void)
{
   printf("\n"WHT"Copyright 1996-7, TGGH, Incorporated - http://www.tggh.net/\n");
}

void do_who(void)
{
   int i;
   char flag;
   char date [ 40 ];

   printf("Port User Name            Logon  Spd From                     Where\n");
   printf("==== ==================== ====== === ======================== ================\n");

   for(i = 0; i <= myp->HiPort; i++)
   {
      if(!myp->pc[i].online)
      {
         continue;
      }
      if(!myp->PortZ[i]->id || (myp->PortZ[i]->IUCBits[i] & PORTRIGHT_HIDDEN) || (myp->PortZ[i]->HideAll))
      {
         if(!myp->gc.SkipIdlePorts)
         {
            char *who = myp->FirstTT->bm[902];
            if(*myp->PortZ[i]->PDE->sp.IdleWho)
            {
               who = myp->PortZ[i]->PDE->sp.IdleWho;
            }
            printf(WHT"%2d   %-20s          0                          "CYN"%-s\n", i, who, myp->FirstTT->bm[906]);
         }
         continue;
      }
      flag = ' ';
      if(myp->PortZ[i]->user1.MyPrivs.ABits2 & SUPERUSER_FLAG)
      {
         flag = *myp->FirstTT->bm[947];
      }
      if(myp->PortZ[i]->user1.MyPrivs.ABits & CONFCON_FLAG)
      {
         flag = *myp->FirstTT->bm[924];
      }
      printf(WHT"%2d "CYN"%c "WHT"%-20s ", i, flag, myp->PortZ[i]->user1.Handle);
      CNetPrintDate(&myp->PortZ[i]->user1.ConnectDate, date, NULL, NULL);
      printf("%6.6s %3d ", date+16, (myp->PortZ[i]->CurrentCPS)/10);
      printf(CYN"%-20.20s %3s ", myp->PortZ[i]->user1.CityState, myp->PortZ[i]->user1.Country);
      printf("%s\n", myp->PortZ[i]->MyDoing);
      if(*myp->PortZ[i]->user1.Banner)
      {
         printf("                                     "PUR"%-s\n", myp->PortZ[i]->user1.Banner);
      }
   }
   return;
}

void main(int argc, char **argv)
{
   int sock = init_inet_daemon();

   if(sock >= 0)
      set_socket_stdio(sock);

   if(CNet4Base = OpenLibrary("cnet4.library", 4))
   {
      Forbid();
      if (myp = (struct MainPort *)FindPort("cnetport"))
      {
         Permit();
         
         do_head();
         do_who();
         do_foot();
      }
      else
      {
         Permit();
         do_head();
         printf("Could not find CONTROL process!\n\n");
         do_foot();
      }
      CloseLibrary(CNet4Base);
   }
}
