/*
 * a version of update that understands bdflush()
 */
static const char rcsid[] = "Mastodon $Id: s.bdflush.c 1.4 99/05/01 19:01:32-00:00 orc $";

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <linux/fs.h>
#include <syslog.h>

_syscall2(int, bdflush, int, func, long, data);

#define DEFAULT_INTERVAL	5

main(int argc, char **argv)
{
    pid_t pid;
    int interval = (argc > 1) ? atoi(argv[1]) : DEFAULT_INTERVAL;
    int x;

    if (getuid() != 0) {
	sync();
	exit(0);
    }

    openlog("update", LOG_PID, LOG_DAEMON);

    if (interval < 1) {
	syslog(LOG_ERR, "Bogus update interval [%s]; setting to %d\n",
			 argv[1], DEFAULT_INTERVAL);
	interval = DEFAULT_INTERVAL;
    }

    if ((pid=fork()) == 0)
	setsid();
    else {
	sleep(1);
	exit(0);
    }

    chdir("/");

    memset(argv[0], 0, strlen(argv[0]));
    
    if ((pid = fork()) > 0) {
	/* parent: try to start the bdflush(2) system process
	 */
	strcpy(argv[0], "(bdflush)");
	sleep(1);

	bdflush(0, 0);
	exit(0);
    }

    /* child: periodically do bdflush(1,0) to tickle the
     *        kernel.
     */
    
    if (interval < DEFAULT_INTERVAL)
	interval = DEFAULT_INTERVAL;
	
    strcpy(argv[0], "(update)");
    while (1) {
	if (bdflush(1, 0) != 0)
	    sync();
	sleep(interval);
    }
} /* update */
