/*
 *  hap -- a mail notification program
 * 
 *  copyright 1995 by Eric Fischer, etaoin@uchicago.edu
 * 
 *  copies of hap may be redistributed under the terms of the
 *  GNU public license, copies of which are available from
 *  the Free Software Foundation, 59 Temple Place, Boston, MA
 *  02111 USA.
 *
 */

#include "hap.h"

/**************************************************************************

    SIGNAL HANDLING STUFF

**************************************************************************/

/* give up the ghost.  wait a second, issue a death announcement, then exit */

retsigtype
alas (foo)
	int foo;   /* what is this for? */
{
	/* a statically allocated buffer?!? why?!?

	   well, we're in a signal handler, so it's possible that
	   very bad things would happen if we called malloc, even
	   though we're probably only interrupting sleep() and
	   are about to exit() anyway.

	   80 for possible filename; max 10 digits in a 32-bit int;
	   10 for username (even though it can really only be 8);
	   and 41 for the surrounding text and newline and \0.

	*/

	char buf[80 + 10 + 10 + 41];
	char *bn = mybasename (program);

	if (strlen (bn) > 79) {
		bn[79] = 0;
	}

	/* make sure the screen has time to scroll the process ID
	   list up before we trample over things
	*/

	sleep (1);

	sprintf (buf, "``ouch!'' says %.80s, process id %d, user id %.10s\n",
		bn, getpid(), whoami());

	startmessage();
	spew (buf);
	endmessage();

	exit (1);
}

/* kill all the other programs that have the same name as us.  Used by
   the -k option.
*/

void
diediedie()
{
	FILE *psout = popen (PSCMD, "r");
	char *s;

	if (psout == 0) {
		fprintf (stderr, "%s: can't open command %s\n", program, PSCMD);
		exit (1);
	}

	while ((s = fgetl (psout))) {
		chop (s);

		if (ends (s, mybasename (program))) {
			int pid;

			printf ("%s", s);

			while (*s == ' ') s++;
			pid = atoi (s);

			if (pid == getpid()) {
				printf ("  (that's us)\n");
			} else {
				printf ("\n");
				kill (pid, SIGTERM);
			}
		}
	}

	pclose (psout);
	exit (0);
}

