From c615f6329d5ea41aa37c488e9778dfa517f83ef5 Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Wed, 13 May 2020 13:13:50 +0200
Subject: [PATCH] Push env on restart

---
 inc/common/macro.h  |  3 +++
 inc/lektor/config.h |  4 ++++
 src/commands.c      | 15 +++++++++++++++
 3 files changed, 22 insertions(+)

diff --git a/inc/common/macro.h b/inc/common/macro.h
index 1ba00aa1..da56e358 100644
--- a/inc/common/macro.h
+++ b/inc/common/macro.h
@@ -75,6 +75,9 @@
 #define SELF_EXECUTABLE_FREEBSD         "/proc/curproc/file"
 #define SELF_EXECUTABLE_SOLARIS         "/proc/self/path/a.out"
 
+#define LKT_ENV_RESTART                 "__LKT_RESTART"
+#define LKT_ENV_CURRENT                 "__LKT_CURRENT"
+
 #define LKT_MAX_SQLITE_STATEMENT        1024
 #define PROTECTED_DATABASE              "disk"
 
diff --git a/inc/lektor/config.h b/inc/lektor/config.h
index 22c200b1..e8c89482 100644
--- a/inc/lektor/config.h
+++ b/inc/lektor/config.h
@@ -35,3 +35,7 @@ int config_new(volatile sqlite3 *db, const char *conf);
 
 /* Prints the default config file. */
 void config_default(FILE *output);
+
+/* Manipulate Environment Variables */
+#define env_set(var, val)   setenv(var, val, 1)
+#define env_get             getenv
diff --git a/src/commands.c b/src/commands.c
index 9ad34084..f4f0c7cf 100644
--- a/src/commands.c
+++ b/src/commands.c
@@ -23,12 +23,27 @@ inline bool
 command_restart(struct lkt_state *srv, size_t c)
 {
     const char *const argv[] = { executable_name, NULL };
+    struct lkt_queue_state sta = {0};
     RETURN_UNLESS(lkt_client_auth(srv, c, false), "Failed to authentificate user", false);
     if (!executable_name) {
         LOG_ERROR_SCT("GENERAL", "%s", "Can't restart if the executable path was not found at start-up");
         return false;
     }
     close(srv->fds[0].fd);
+    database_queue_state(srv->db, &sta);
+    env_set(LKT_ENV_RESTART, "1");
+    int len = long_length(sta.current);
+    if (len > 0) {
+        char *pos = calloc(len, sizeof(char));
+        if (pos) {
+            safe_snprintf(pos, len, "%d", sta.current);
+            env_set(LKT_ENV_CURRENT, pos);
+            free(pos);
+        } else
+            LOG_WARN_SCT("GENERAL", "Failed to malloc, don't set %s to %d",
+                         LKT_ENV_CURRENT, sta.current);
+    } else
+        env_set(LKT_ENV_CURRENT, "NULL");
     database_close_all();
     execv(executable_name, (char *const *) argv);
     LOG_ERROR_SCT("GENERAL", "%s", "Failed to exec lektor or OS not supported");
-- 
GitLab