#!/bin/bash

# Takes a filename (full path) and an agent name.
# Then waits for the file to exist and be executable, at which point we tickle
# the Launcher by toggling <sysdb-path/agent>.stable, which will cause Launcher to 
# continue where it left off because the file (the executable) was missing.
# This is useful to allow for pre-configuration in cases like CLI:
# "daemon <name>; exec /usr/bin/not-here-yet <args>".
# Which, besides the convenience, seems to be required in some ASU cases.

# Enable traces if sentinel file is created (trace go into the sentinel file)
if [ -e /tmp/debug_LauncherWaitExe ]; then
   exec &> /tmp/debug_LauncherWaitExe
else
   exec &> /dev/null
fi

if [ "$#" != 2 ]; then
   echo "[LauncherWaitExe] Error: missing argument: <agent-name> <binary-to-run>"
   exit -1
fi

agent=$1
shift
bin=$1

# wait for the file to exist
if [ ! -e "$bin" ]; then
   echo "[LauncherWaitExe] Waiting for $bin to exist."
   dir=$(dirname $bin)
   file=$(basename $bin)
   # create dir if needed, inotifywait needs that
   mkdir -p $dir || exit -1
   while res=$(inotifywait -e create $dir); do
      newFile=${res##*CREATE }
      newFile=${newFile%%;*}
      if [ "$file" == "$newFile" ]; then
         break
      fi
   done
fi

# wait for the file to become executable
if [ ! -x "$bin" ]; then
   echo "[LauncherwaitExe] Waiting for $bin to become executable."
   while res=$(inotifywait -e attrib $bin); do
      if [ -x "$bin" ]; then
         break
      fi
   done
fi
echo "[LauncherwaitExe] launching $bin."

# now tickle Launcher to continue its processing of the binary now that it is avail
sysname=${SYSNAME:-ar}
python=${PYTHON:-arista-python}
printf "cd /${sysname}/Sysdb/sys/config/cli/agentConfigDir/agent/${agent}\n_.stable=False"\
 | ${python} -m Acons Sysdb
printf "cd /${sysname}/Sysdb/sys/config/cli/agentConfigDir/agent/${agent}\n_.stable=True"\
 | ${python} -m Acons Sysdb

