/* Public domain. */

#include <sys/types.h>
#include <sys/file.h>
#ifdef BSD
#include <limits.h>
#endif
#include <sys/dir.h>
#include <stdio.h>
#include "sessutil.h"
extern unsigned short getuid();

main()
{
 int uid;
 DIR *dirp;
 struct direct *dp;
 int fd;
 int intbuf[100];
 char *buf = (char *) intbuf;
 int r;

 uid = getuid();

 if (pty_sessdir(uid) == -1)
  {
   (void) fputs("sesslist: fatal: cannot change to session directory\n",stderr);
   (void) exit(1);
  }
 dirp = opendir(".");
 while (dp = readdir(dirp))
  {
   if (!strncmp(dp->d_name,"re.",3))
     (void) printf("session %s disconnected\n",dp->d_name + 3);
   else if (!strncmp(dp->d_name,"sess.",5))
    {
     if ((fd = open(dp->d_name,O_RDONLY)) == -1)
       (void) fprintf(stderr,
	      "sesslist: warning: cannot open %s\n",dp->d_name);
     else
      {
       r = read(fd,buf,99); /* anything up to sizeof(intbuf) - 1 */
       if (r < 4 * sizeof(int))
         (void) fprintf(stderr,
	        "sesslist: warning: cannot read %s\n",dp->d_name);
       else if (r == 4 * sizeof(int))
	 (void) printf("session %s sigler %d master %d slave %d\n",
		dp->d_name + 5,intbuf[1],intbuf[2],intbuf[3]);
       else
	{
	 buf[r] = '\0';
	 (void) printf("session %s sigler %d master %d slave %d: %s\n",
		dp->d_name + 5,intbuf[1],intbuf[2],intbuf[3],
		buf + 4 * sizeof(int));
	}
       (void) close(fd);
      }
    }
   else if (!strncmp(dp->d_name,"sig.",4))
    {
     if ((fd = open(dp->d_name,O_RDONLY)) == -1)
       (void) fprintf(stderr,
	      "sesslist: warning: cannot open %s\n",dp->d_name);
     else
      {
       r = read(fd,buf,99);
       if (r < 9)
         (void) fprintf(stderr,
	        "sesslist: warning: cannot read %s\n",dp->d_name);
       else
	{
	 buf[r] = '\0';
	 (void) printf("session %s will drop into session %s\n",
		dp->d_name + 4,buf + 8);
	}
       (void) close(fd);
      }
    }
   else if (!strncmp(dp->d_name,".",1))
     ;
   else if (!strncmp(dp->d_name,"..",2))
     ;
   else
     (void) fprintf(stderr,
	    "sesslist: warning: unknown file type %s\n",dp->d_name);
  }
 (void) exit(0);
}
