#include "pid.h"

static int	fdpid = -1;
static FILE	*fpid = NULL;

int	create_pid_file(const char *pidfile)
{
	int		fd;
	struct stat	buf;
	struct flock	fl;

	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = getpid();

	/* check if pid file already exists */
	if (0 == stat(pidfile, &buf))
	{
		if (-1 == (fd = open(pidfile, O_WRONLY | O_APPEND)))
		{
			printf("cannot open PID file [%s]: %d", pidfile, errno);
			// Log output
			// zbx_error("cannot open PID file [%s]: %s", pidfile, zbx_strerror(errno));
			return FAIL;
		}

		if (-1 == fcntl(fd, F_SETLK, &fl))
		{
			close(fd);
			printf("Is this process already running? Could not lock PID file [%s]: %d", pidfile, errno);
			// Log output
			// zbx_error("Is this process already running? Could not lock PID file [%s]: %s",
					// pidfile, zbx_strerror(errno));
			return FAIL;
		}

		close(fd);
	}

	/* open pid file */
	if (NULL == (fpid = fopen(pidfile, "w")))
	{
		printf("cannot create PID file [%s]: %d", pidfile, errno);
		//Log output
		// zbx_error("cannot create PID file [%s]: %s", pidfile, zbx_strerror(errno));
		return FAIL;
	}

	/* lock file */
	if (-1 != (fdpid = fileno(fpid)))
	{
		fcntl(fdpid, F_SETLK, &fl);
		fcntl(fdpid, F_SETFD, FD_CLOEXEC);
	}

	/* write pid to file */
	fprintf(fpid, "%d", (int)getpid());
	fflush(fpid);

	return SUCCEED;
}

void	drop_pid_file(const char *pidfile)
{
	struct flock	fl;

	fl.l_type = F_UNLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = jaz_get_thread_id();

	/* unlock file */
	if (-1 != fdpid)
		fcntl(fdpid, F_SETLK, &fl);

	/* close pid file */
	jaz_fclose(fpid);

	unlink(pidfile);
}