/* fake-acct
 * An ld preload library to fake the libc wrapper for the acct(2) syscall
 * and enable fake process accounting generation using gen-acct.
 *  -- Andrew Bower <andrew@bower.uk>  Thu, 19 Jun 2025 07:27:24 +0100
 */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static const char *tool = "/usr/local/bin/gen-acct";
static const char *lock = "/run/gen-acct.pid";

int acct(const char *filename) {
  char *cmd;
  int rc;

  if (filename) {
    if ((rc = asprintf(&cmd, "%s %s %s", tool, lock, filename)) != -1) {
      rc = system(cmd);
      free(cmd);
    }
  } else {
    if ((rc = access(lock, R_OK | W_OK)) != -1) {
      FILE *pidf = fopen(lock, "r");
      pid_t pid;
      if (pidf == NULL)
        return -1;
      if (fscanf(pidf, "%d", &pid) == 1) {
        if (pid > 0) {
          rc = kill(pid, SIGTERM);
        } else {
          rc = -1;
	  errno = ESRCH;
        }
      }
      fclose(pidf);
      unlink(lock);
    }
  }
  return rc;
}
