/*
 * This program is useful for opendnssec's NotifyCommand when using nsd.
 * It should be setuid root.
 * 
 * Authored by Russell Harmon <russ@eatnumber1.com>
 */

#define _XOPEN_SOURCE
#define _XOPEN_SOURCE_EXTENDED

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

static void spawn( char * const argv[] ) {
	pid_t pid = fork();
	if( pid == -1 ) {
		perror("fork");
		exit(EXIT_FAILURE);
	} else if( pid == 0 ) {
		// Child
		execv(argv[0], argv);
		perror("execvp");
		exit(EXIT_FAILURE);
	} else {
		// Parent
		siginfo_t siginfo;
		if( waitid(P_PID, pid, &siginfo, WEXITED) == -1 ) {
			perror("waitid");
			exit(EXIT_FAILURE);
		}
		if( siginfo.si_code != CLD_EXITED || siginfo.si_status != EXIT_SUCCESS ) {
			fprintf(stderr, "Abnormal child exit\n");
			exit(EXIT_FAILURE);
		}
	}
}

int main() {
	if( setuid(0) == -1 ) {
		perror("setuid");
		exit(EXIT_FAILURE);
	}
	char *args[3] = { [2] = NULL };
	char **command = &args[1], **binary = &args[0];
	*binary = "/usr/sbin/nsd-control";

/*
	*command = "rebuild";
	spawn(args);
*/
	*command = "reload";
	spawn(args);
	*command = "notify";
	spawn(args);
	return EXIT_SUCCESS;
}
