/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
 * Copyright (c) Red Hat, Inc. All rights reserved. This copyrighted material
 * is made available to anyone wishing to use, modify, copy, or
 * redistribute it subject to the terms and conditions of the GNU General
 * Public License v.2.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <dirent.h>

int
main(int argc, char **argv)
{
    char buffer[1024], buf[1024];
    FILE *fpr, *fpw;
    pid_t ppid;
    size_t size;
    struct stat st;

    if (argc < 3) {
	printf("Usage: %s <pid> <signum>\n"
	       "store the gdb debugging logs for <pid> to %s\n", argv[0], LOGDIR "/segvYYYYMMDDhhmmss.log");
	exit(1);
    }
    ppid = getppid();
    if (ppid != atoi(argv[1])) {
	fprintf(stderr, "the parent process id %d and the given pid %s is different.\n", ppid, argv[1]);
	exit(1);
    }
    if (stat(DATADIR "/gdbcmd", &st) == -1) {
	fprintf(stderr, "cannot find the command list file `%s' for gdb.\n", DATADIR "/gdbcmd");
	exit(1);
    }

    snprintf(buffer, 1024, "gdb --batch --quiet --command %s/gdbcmd --pid %d",
	     DATADIR, ppid);

    if ((fpr = popen(buffer, "r")) != NULL) {
	char logfile[PATH_MAX];
	time_t t = time(NULL);
	struct tm tm;

	if (stat(LOGDIR, &st) == -1) {
	    if (errno == ENOENT) {
		/* make the log directory */
		mkdir(LOGDIR, 0755);
	    }
	}

	tm = *localtime(&t);
	snprintf(logfile, PATH_MAX, "%s/segv%04d%02d%02d%02d%02d%02d.log", LOGDIR, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
	if ((fpw = fopen(logfile, "w")) != NULL) {
	    fprintf(fpw, "==================================================\nProcess %d received signal %s\n==================================================\n",
		    ppid, argv[2]);
	    while (1) {
		size = fread(buf, sizeof (char), 1024, fpr);
		fwrite(buf, sizeof (char), size, fpw);
		if (size < 1024) {
		    fputs("\n", fpw);
		    break;
		}
	    }

	    fclose(fpw);
	} else {
	    fprintf(stderr, "failed to open the log file `%s'.\n", logfile);
	}
	pclose(fpr);
    } else {
	fprintf(stderr, "failed to fork\n");
    }

    return 0;
}
