/*
 *	Copyright 1988 by Rayan S. Zachariassen, all rights reserved.
 *	This will be free software, but only when it is finished.
 */

#include "hostenv.h"
#include "mailer.h"
#include <signal.h>

#ifndef	_IOFBF
#define	_IOFBF	0
#endif	/* !_IOFBF */

/* send a signal to an already-running daemon process or process group */

void
killprevious(sig, pidfile)
	int sig;
	char *pidfile;
{
	int c;
	FILE *fp;
	char *path, buf[128];
	extern char *postoffice;

	path = emalloc((unsigned)(strlen(postoffice) + strlen(pidfile) + 2));
	(void) sprintf(path, "%s/%s", postoffice, pidfile);
	if (sig != 0 && (fp = fopen(path, "r")) != NULL) {
		(void) setvbuf(fp, buf, _IOFBF, sizeof buf);
		if (fscanf(fp, "%d", &c) != 1)
			(void) fprintf(stderr,
				"couln't make sense of contents of %s!\n",
				path);
		else if (c == getpid())
			(void) printf("was about to commit suicide\n");
		else if ((sig < 0 && kill(-c, -sig) == 0 && sig == -SIGTERM)
			 || (sig > 0 && kill(c, sig) == 0 && sig == SIGTERM)) {
			printf("killed previous daemon%s = %d\n",
				(sig > 0) ? ", pid" : "s, pgrp", c);
			sleep(3);	/* give process time to die */
		}
		(void) fclose(fp);
	}
	if ((sig == 0 || sig == SIGTERM || -sig == SIGTERM)
	    && (fp = fopen(path, "w+")) != NULL) {
		(void) setvbuf(fp, buf, _IOFBF, sizeof buf);
		(void) fprintf(fp, "%d\n", getpid());
		(void) fclose(fp);
	}
	free(path);
}
