/* $Id: daemonize.C,v 1.5 2001/11/02 16:07:37 dm Exp $ */

/*
 *
 * Copyright (C) 1999 David Mazieres (dm@uun.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

#include "async.h"

str syslog_priority ("daemon.notice");

static void
start_logger ()
{
#ifdef PATH_LOGGER
  char *av[] = { PATH_LOGGER, "-p",
		 const_cast<char *> (syslog_priority.cstr ()),
		 "-t", "", NULL};
  int fds[2];

  close (0);
  if (int fd = open ("/dev/null", O_RDONLY))
    close (fd);

  if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
    fatal ("socketpair: %m\n");
  close_on_exec (fds[0]);
  if (fds[1] != 0)
    close_on_exec (fds[1]);

  if (spawn (PATH_LOGGER, av, fds[1], 0, 0) >= 0) {
    close (fds[1]);
    if (fds[0] != errfd) {
      err_flush ();		// XXX - we shouldn't depend on aerr.C
      if (dup2 (fds[0], errfd) < 0)
	fatal ("dup2: %m\n");
      close (fds[0]);
    }
    if (errfd != 1)
      dup2 (errfd, 1);
    return;
  }
  else
    warn ("%s: %m\n", PATH_LOGGER);
#endif /* PATH_LOGGER */
  
  /* No logger, at least send chatter to stdout rather than stderr, so
   * that it can be redirected. */
  dup2 (errfd, 1);
}

void
daemonize ()
{
  switch (fork ()) {
  default:
    _exit (0);
  case -1:
    fatal ("fork: %m\n");
  case 0:
    break;
  }
    
  if (setsid () < 0)
    fatal ("setsid: %m\n");
  if (!builddir) {
    start_logger ();
    str2file (strbuf () << PIDDIR << "/" << progname << ".pid",
	      strbuf ("%d\n", getpid ()), 0444);
  }
  else {
    str piddir = buildtmpdir;
    if (!piddir)
      piddir = builddir;
    str2file (strbuf () << buildtmpdir << "/" << progname << ".pid",
	      strbuf ("%d\n", getpid ()), 0444);
  }
}
