/*-
 * Copyright (c) 2004 Free (Olivier Beyssac)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include "options.h"
#include "daemon.h"

#define MAXFD (16)


extern struct options opt;


static void write_pid(void)
{
   FILE *f;

   if ((f = fopen(opt.pid_filename, "w")) == NULL) {
     syslog(LOG_ERR, "fopen %s: %s", opt.pid_filename, strerror(errno));
     exit(EXIT_FAILURE);
   }
   else {
     fprintf(f, "%i\n", getpid());
     fclose(f);
   }
}


/* Mostly from Unix Network Programming */
extern void daemon_init(void)
{
   int i;
   pid_t pid;
   
   if ((pid = fork()) != 0)
     exit(EXIT_SUCCESS);         /* parent terminates */
   
   /* 1st child continues */
   setsid();                     /* become session leader */
   
   signal(SIGHUP, SIG_IGN);
   if ((pid = fork()) != 0)
     exit(EXIT_FAILURE);         /* 1st child terminates */

   write_pid();
   
   /* 2nd child continues */
   chdir(opt.working_dir);       /* change working directory */
   
   umask(0);                     /* clear our file mode creation mask */
   
   for (i = 0; i < MAXFD; i++)
     close(i);
}
