#!/bin/sh
# link: https://github.com/hashicorp/consul/issues/3182
# author: Yann "aya" Autissier
# license: GPL
set -eu

DOCKER_SOCK=${DOCKER_SOCK:-/var/run/docker.sock}

if ! which curl > /dev/null || ! which jq >/dev/null; then
  >&2 echo "ERROR: curl or jq not found"
  exit 2
fi

if [ $# -ne 1 ]; then
  >&2 echo "ERROR: invalid parameter '$*'"
  echo "USAGE: $0 container-id|container-name|container-ip"
  exit 2
fi

{
 {
  {
    # list all dockers
    for docker in $(curl --disable --fail --show-error --silent --unix-socket "${DOCKER_SOCK}" http://localhost/containers/json |jq -r '.[].Id'); do
      # print "health_status id name ip_address health_output" for each docker
      curl --disable --fail --show-error --silent --unix-socket "${DOCKER_SOCK}" "http://localhost/containers/${docker}/json" \
       |jq -r '[.State.Health.Status, .Id, .Name, .NetworkSettings.IPAddress, .State.Health.Log[0].Output] |@tsv'
              # shorten id: .Id |capture("(?<id>.{12})").id
    # print "health_status" and "health_output" for line matching $1
    done |awk -F '\t' '/\<'"$1"'\>/ {print $1 | "cat >&3; exec 3>&-"; print $NF | "cat >&4";}'
  } 3>&1
 } | {
  read -r status ||:
  case "$status" in
    healthy) exit=0;;
    starting) exit=1;;
    *) exit=2;;
  esac
  # exit according to "health_status"
  exit $exit
 }
# print "health_output"
} 4>&1
