#!/bin/bash

LOCATION="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

INTERVAL=${INTERVAL:-60}

# track pid with a file `autoheal.pid`. If a previous instance is still running, exit early.
function cleanup() {
  rm -f ${LOCATION}/autoheal.pid
}
trap cleanup EXIT
kill -0 $(cat ${LOCATION}/autoheal.pid 2> /dev/null) 2> /dev/null && echo "autoheal script already running" && exit 1
echo $$ > ${LOCATION}/autoheal.pid

# exit on SIGINT
trap exit INT

# run at fixed interval, checking for and restarting any service marked as 'unhealthy'
pushd $LOCATION > /dev/null
  while [ 1 ]; do
    # get current state (running or not) and status (healthy, unhealthy, etc)
    app_state=$(docker compose ps --format '{{.State}}' streamline-emr)
    app_status=$(docker compose ps --format '{{.Status}}' streamline-emr)

    # check if app is running and healhty
    if [ "${app_state}" = "running" ]; then
      if [[ "${app_status}" = *\(unhealthy\) ]]; then
        echo "Unhealthy service detected. Restarting 'streamline-emr'"
        docker compose restart streamline-emr
      fi
    # app should be running - restart
    else
      echo "Container not running. Starting 'streamline-emr'"
      docker compose up -d streamline-emr
    fi

    # wait a little while before checking again
    sleep $INTERVAL
  done
popd > /dev/null