/*
 * $Header: /cvsroot/csrc/continuity/cont/cdog.c,v 1.4 2004/03/18 15:04:15
 * aleigh Exp $
 */

/*
 * Copyright (c) 1994, 2004 Alex Leigh, All Rights Reserved
 * 
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ALEX LEIGH The copyright
 * notice above does not evidence any actual or intended publication of such
 * source code.
 * 
 * Disclosure, copying, distribution, or transmission of this code without
 * express permission is prohibited.
 */

#include <sys/wait.h>
#include <signal.h>

#include "csys.h"

#define CBIN "./continuity"

static void print_usage(void);

static void print_usage(void)
{
    printf("For Continuity startup options, run cdog -h\n");
}

int main(int argc, char **argv)
{
    int status;
    char **alist;
    int acount;

    if (argc == 1) {
        print_usage();
        exit(0);
    }
    
        /* Prevent Continuity from daemonizing which will cause
           us to lose track of it's PID */
    
    if(fork()!=0) {
        exit(0);
    }

    setsid();
    
    if(fork()!=0) {
        exit(0);
    }

    printf("Continuity Watchdog v1.0.2\n");

    putenv((char *)"__CONT_NODAEMON=true");

    signal(SIGHUP, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    acount = argc + 1;
    alist = (char **) malloc(acount * sizeof(char *));
    bzero(alist, acount * sizeof(char *));
    bcopy(argv, alist, argc * sizeof(char *));
    alist[0] = (char *) CBIN;

    while (1) {
	if (fork() != 0) {
	    wait(&status);
	    if (WIFEXITED(status)) {
		printf("cdog: Continuity exited, status %d.\n",
		       WEXITSTATUS(status));
		if (WEXITSTATUS(status) == 5) {
		    printf("cdog: Continuity requested exit.\n");
		    exit(0);
		}
		if (WEXITSTATUS(status) == 6) {
		    printf("cdog: Could not start server. Exiting.\n");
		    exit(0);
		}
	    }
	    continue;
	}
	if (execvp(CBIN, alist) == -1)
	    exit(6);
    }
}
