/*
 * reporter.c
 *
 * This program gathers some information about people who have logged
 * in this computer by using the who command. It sends the results to the 
 * admin program.
 *
 * By Kamran Karimi.
 */

#include "admin.h"

void main()
{
 int count, msgid;
 struct message mess;
 char cmd[80];
 char filename[40];
 struct utsname utsn;
 FILE *fptr;

 /* get some information about this computer. The admin will use it
    to differentiate between different machines */ 
 if(uname(&utsn) < 0)
 {
  fprintf(stderr,"Reporter: Can not get information about the system\n");
  exit(20);
 }
#ifdef __GLIBC__
 if(strlen(utsn.nodename) + strlen(utsn.__domainname) >= SPEC_SIZE)
#else
 if(strlen(utsn.nodename) + strlen(utsn.domainname) >= SPEC_SIZE)
#endif
 {
  fprintf(stderr, "Reporter: Length of machine's name is too big\n");
  exit(20);
 } 
#ifdef __GLIBC__
 sprintf(mess.body.spec,"%s.%s",utsn.nodename, utsn.__domainname);
#else
 sprintf(mess.body.spec,"%s.%s",utsn.nodename, utsn.domainname);
#endif 
 /* create a unique file name (more than one instance of reporter may be
    running in the same computer) */
 sprintf(filename,"%s%d", REPORTER_FILE_NAME, getpid());
 
 sprintf(cmd,"who -H >%s", filename); /* <--- THIS is the command */

 msgid = msgget(MSG_KEY, MSG_MODE);
 if(msgid < 0) 
 {
  fprintf(stderr,"Reporter: msgget() failed: %s\n",strerror(errno));
  exit(20);
 }
 mess.mtype = MSG_TYPE; /* not necessary here */
 mess.body.architecture = MY_DIPC_ARCH;
 while(1) /* loop until interrupted */
 {
  system(cmd);
  fptr = fopen(filename,"r");
  mess.body.type = FIRST; /* the first message... */
  do
  {
   count = 0;
   while(!feof(fptr) && count < MSG_SIZE)
   {
    mess.body.mtext[count] = fgetc(fptr);
    count++;
   }
   if(feof(fptr)) 
   {
    mess.body.done = 1;
    mess.body.mtext[count - 1] = 0;
   }
   else 
    mess.body.done = 0; 
   
   if(msgsnd(msgid, (struct msgbuf *)&mess, sizeof(struct body), 0) < 0)
   {
    fprintf(stderr,"Reporter: msgsnd() failed BECAUSE %s\n", strerror(errno));
    exit(20);
   }
   mess.body.type = CONTINUE;
  } while(!feof(fptr)); 
  fclose(fptr);
  unlink(filename);
  sleep(REPORTER_SLEEP_TIME);
 }
 exit(0);
}
