// Suddenly RepetierHost started refusing to run when I tried to
// start it from the udev scripts for my 3d printer.
//
// I gave up trying to understand why, and now I'm writing this
// stupid program to use inotify to notice when a file is touched
// and start RepetierHost.

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <sys/inotify.h>

#define MAGIC_FILE "/home/tom/.stoopid"

int
main(int argc, char ** argv) {
   struct inotify_event ev;

   int fd = inotify_init1(IN_CLOEXEC);
   inotify_add_watch(fd, MAGIC_FILE, IN_ATTRIB);
   int len;
   for ( ; ; ) {
      len = read(fd, (void *)&ev, sizeof(ev));
      if (len == sizeof(ev)) {

         // I'm only watching one file for one event, start
         // RepetierHost on a successful read.

         pid_t kid = fork();
         if (kid == 0) {
            execl("/usr/local/bin/bg-dammit", "/usr/local/bin/bg-dammit",
                  "/home/tom/scripts/RepetierHost", NULL);
            _exit(2);
         } else {
            int status;
            waitpid(kid, &status, 0);
         }
      } else {
         if ((len != -1) || (errno != EINTR)) {
            // Weird error, get out of here.
            break;
         }
      }
   }
   return 0;
}
