From 3e56feb350458dc930fe22efd7f535c107dda080 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Romain=20Bron=C3=A8s?=
 <romain.broucquart@synchrotron-soleil.fr>
Date: Thu, 14 Dec 2023 17:13:21 +0100
Subject: [PATCH] fix(opcua): Start deamon exit when server fails to start

---
 .../files/fofb-opcua-server.sh                | 33 ++++++++++++++-----
 1 file changed, 25 insertions(+), 8 deletions(-)

diff --git a/recipes-app/fofb-opcua-server/files/fofb-opcua-server.sh b/recipes-app/fofb-opcua-server/files/fofb-opcua-server.sh
index 478e2b8..ec2a511 100755
--- a/recipes-app/fofb-opcua-server/files/fofb-opcua-server.sh
+++ b/recipes-app/fofb-opcua-server/files/fofb-opcua-server.sh
@@ -23,16 +23,33 @@ start() {
     echo "starting" > $LOCK_FILE
     stdbuf -oL opcua-generic-chimeratk-server01 &>> $LOG_FILE &
 
-    # Wait for server started
-    (tail -F -n0 $LOG_FILE & ) | grep -q "All application modules are running"
+    (tail -F -n0 $LOG_FILE & ) | grep -q "ChimeraTK::logic_error" && (echo "crashed" > $LOCK_FILE) &
+    (tail -F -n0 $LOG_FILE & ) | grep -q "All application modules are running" && (echo "started" > $LOCK_FILE) &
 
-    # Restart FPGA application because server writes all zeros
-    echo "Restart FPGA application" >> $LOG_FILE
-    /etc/init.d/fofb-init.sh start
+    # Wait for server started or crashed
+    while :
+    do
+        state=$(cat $LOCK_FILE)
+        if [ "$state" = "started" ] ; then
+
+            # Reset the FPGA
+            echo "Init again application" >> $LOG_FILE
+            /etc/init.d/fofb-init.sh start >> $LOG_FILE
+
+            success
+            break
+        fi
+
+        if [ "$state" = "crashed" ] ; then
+            failure
+            break
+        fi
+
+        sleep 1
+    done
+
+    kill $(jobs -p)
 
-    ### Create the lock file ###
-    echo "started" > $LOCK_FILE
-    success $"fofb-opcua server startup"
 }
 
 
-- 
GitLab