/* ------------------------------------------------------------------- */
/* Copyright (C) 2014 by Sascha Wilde <wilde@sha-bang.de> */

/* This program is free software under the GNU GPL (>=v2) */
/* Read the file COPYING coming with the software for details. */
/* ------------------------------------------------------------------- */

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int create_lock(char* id)
{
  /* Claim uid specific lockfile with id being an arbitrary string. 
   * Returns flock files fd on success.  Or -1 on failure.          */
  int fd;
  uid_t uid = getuid();
  pid_t pid = getpid();
  char lockfile[128];
  char pidstr[21];
    
  snprintf(lockfile, 128, "/var/lock/%s-%d.lock", id, uid);

  if (((fd = open(lockfile, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)) != -1) &&
      (flock(fd, LOCK_EX|LOCK_NB) == 0))
    {
      snprintf(pidstr, 21, "%d", pid);
      ftruncate(fd, 0);
      write(fd, pidstr, strlen(pidstr));
      return fd;
    }
  else
    {
      warn("Could not grab lock file %s", lockfile);
      if (fd != -1)
        close(fd);
      return -1;
    }
}

void remove_lock(int fd)
{
  close(fd);
}
