/* Public domain. */

#include <sys/types.h>
#include <sys/timeb.h>
#include <sys/file.h>
#ifdef BSD
#include <limits.h>
#endif
#include <stdio.h>
#include <strings.h>
#include <utmp.h>
#include <pwd.h>
#include <time.h>
#include <ctype.h>
extern unsigned short getuid();
extern char *ttyname();
extern long time();
#define PTYUTMP_FILE "/etc/utmp"

main()
{ 
 register FILE *fi;
 struct utmp ut;
 char fntty[30];
 int fd;
 char buf[10000];
 char *username;
 struct passwd *pw;
 char hostname[64];
 char *ttyn;
 long t;
 struct tm *tm;
 int r;
 int pos;

 if (!(pw = getpwuid((int) getuid())))
  {
   (void) fprintf(stderr,"write: who are you?\n");
   (void) exit(1);
  }
 username = pw->pw_name;

 (void) gethostname(hostname,sizeof(hostname));

 if (!(ttyn = ttyname(2)))
  {
   (void) fprintf(stderr,"wall: Can't find your tty\n");
   (void) exit(1);
  }

 t = time((long *) 0);
 tm = localtime(&t);

 (void) sprintf(buf,"\nBroadcast message from %s@%s on %s at %d:%02d ...\n\n",
		username,hostname,ttyn + 5,tm->tm_hour,tm->tm_min);
 pos = strlen(buf);
 (void) write(1,buf + 1,pos - 1);
 while ((pos < 10000) && ((r = read(0,buf + pos,10000 - pos)) > 0))
   pos += r;

 if (fi = fopen(PTYUTMP_FILE,"r"))
   while (fread((char *) &ut,sizeof(ut),1,fi))
     if (ut.ut_name[0])
      {
       (void) sprintf(fntty,"/dev/%.8s",ut.ut_line);
       if ((fd = open(fntty,O_WRONLY)) == -1)
         (void) fprintf(stderr,"wall: cannot write to %.8s\n",ut.ut_line);
       else
        {
	 (void) write(fd,buf,pos);
         (void) close(fd);
        }
      }

 (void) exit(0);
}
