#!/bin/bash

# Takes a script (full path) and its arguments.
# Then waits for the script to exist and be executable.
# Then execs the script (at which point our name in ps output will change).
# That is, we are a wrapper that waits for the real script to show up, which is
# useful if this run as part of a running-config and is executed ahead of the
# extension that installs the real script, or also to allow for pre-configuration.
# Intended usage for CLI: "daemon <name>; exec /usr/bin/RunOnExists <script> <args>".
# If no <script> is provided (the deamon command syntax allows that), this will 
# exit immediatly and ProcMgr will periodically try again; log in /var/log/agents
# will show a clue to what is going on.

if [ "$#" == 0 ]; then
   echo "[RunOnExists] Error: missing argument: <binary to run> [<arg> ...]"
   echo "[RunOnExists] For example: /usr/bin/myApp 1.1.1.1"
   exit -1
fi

bin=$1
shift

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

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

# now launch it
echo "[RunOnExists] Exec-ing $bin."
exec $bin "$@"


