/*
 * zpunt -- punt a specific <message,instance,recipient> triple.  Works
 * only with the new zwgc (by marc@athena and company).  This program is
 * a hack that is only designed to last until the "punt" command is added
 * to zctl.  If you find a bug, feel free to tell me about it.  I might
 * even fix it.
 *
 * Written by Barr3y Jaspan, Student Information Processing Board (SIPB)
 * bjaspan@athena.mit.edu
 */

#include <stdio.h>
#include <zephyr/zephyr.h>

char *whoami, *rindex();

main(argc, argv)
   int argc;
   char **argv;
{
     int	retval, punt;
     short	newport;
     char	*class, *inst, *recip, *msg;
     struct sockaddr_in	newsin;
     ZNotice_t	notice;

     whoami = ((whoami = rindex(argv[0], '/')) ? whoami+1 : argv[0]);
      
     if (! strcmp(whoami, "zpunt")) punt = 1;
     else punt = 0;

     switch (argc) {
     case 2:
	  class = "MESSAGE";
	  inst = argv[1];
	  recip = "";
	  break;
     case 3:
	  class = argv[1];
	  inst = argv[2];
	  recip = "";
	  break;
     case 4:
	  class = argv[1];
	  inst = argv[2];
	  recip = (*argv[3] == '*' ? "" : argv[3]);
	  break;
     default:
	  Usage();
	  break;
     }

     /* Zephyr initialization */
     retval = ZInitialize();
     if(retval != ZERR_NONE) {
          com_err(whoami, retval, "while initializing Zephyr.");
          exit(1);
     }

     retval = ZOpenPort((int *) 0);
     if(retval != ZERR_NONE) {
          com_err(whoami, retval, "while opening Zephyr port.");
          exit(1);
     }

     newsin = ZGetDestAddr();
     if ((newport = ZGetWGPort()) == -1) {
	  fprintf(stderr, "%s: Can't find windowgram port\n", whoami);
	  exit(1);
     }
     
     newsin.sin_port = (unsigned short) newport;
     if ((retval = ZSetDestAddr(&newsin)) != ZERR_NONE) {
	  com_err(whoami,retval,"while setting destination address");
	  exit(1);
     }

     msg = (char *) malloc(strlen(class) + strlen(inst) + strlen(recip) + 4);
     sprintf(msg, "%s%c%s%c%s", class, '\0', inst, '\0', recip);
     printf("%s <%s,%s,%s>\n", punt ? "Punting" : "Unpunting",
	    class, inst, *recip ? recip : "*");
               
     bzero((char *) &notice, sizeof(ZNotice_t));
     notice.z_kind = UNSAFE;
     notice.z_class = WG_CTL_CLASS;
     notice.z_class_inst = WG_CTL_USER;
     notice.z_recipient = "";
     notice.z_default_format = "";
     notice.z_opcode = (punt) ? "SUPPRESS" : "UNSUPPRESS";
     notice.z_port = 0;
     notice.z_message = msg;
     notice.z_message_len = strlen(class)+strlen(inst)+strlen(recip)+3;

     if ((retval = ZSendNotice(&notice,ZNOAUTH)) != ZERR_NONE)
	  fprintf(stderr,"%s: while sending notice\n",whoami);

     free(msg);
     return 0;
}

Usage()
{
     fprintf(stderr, "Usages:\n");
     fprintf(stderr, "\t%s instance\n", whoami);
     fprintf(stderr, "\t%s class instance\n", whoami);
     fprintf(stderr, "\t%s class instance recipient\n", whoami);
     exit(1);
}
