/* pidfile.c */

/* Copyright 2000 by Eberhard Mattes <em-gw@windhager.de>
   Donated to the public domain.  No warranty.

   2000-04-14 Initial version
   2000-04-29 Use set_userid_groupid() */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include "firewall.h"
#include "libemfw.h"

static const char *pidfile_name;
static FILE *pidfile_file;

static void kill_pid_file (void)
{
  if (pidfile_file)
    {
      if (fclose (pidfile_file) != 0)
	syslog (LLEV, "%s: %s", pidfile_name, strerror(errno));
      pidfile_file = 0;
    }
  if (pidfile_name)
    {
      if (unlink (pidfile_name) != 0)
	syslog (LLEV, "%s: %s", pidfile_name, strerror(errno));
      pidfile_name = 0;
    }
}

void keep_pid_file (void)
{
  pidfile_file = 0;
  pidfile_name = 0;
}

void create_pid_file (const char *s)
{
  pidfile_name = s;
  if (!s)
    return;
  pidfile_file = fopen (pidfile_name, "w");
  if (pidfile_file == NULL)
    {
      syslog (LLEV, "%s: %s", pidfile_name, strerror(errno));
      exit (1);
    }
  atexit (kill_pid_file);
}

void write_pid_file (void)
{
  if (!pidfile_file)
    return;

  fprintf (pidfile_file, "%ld\n", (long)getpid ());
  if (fclose (pidfile_file) != 0)
    {
      pidfile_file = 0;
      syslog (LLEV, "%s: %s", pidfile_name, strerror(errno));
      exit (1);
    }
  pidfile_file = 0;
}
