#!/usr/bin/env bash
#
# Copyright (c) Cognitect, Inc.
# All rights reserved.
set -e

if [ -f /opt/datomic.app.deploy/bin/export-environment ]; then
  . /opt/datomic.app.deploy/bin/export-environment
fi

HC_PORT=${DATOMIC_HEALTH_CHECK_PORT:-8182}

APPLICATION_PID=$(<"${DATOMIC_APPLICATION_PID_FILE}")
echo "Validating ${APPLICATION_PID} running"
kill -0 ${APPLICATION_PID}

LOCAL_IP=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)

if [[ ! -v DISABLE_SSL ]]; then
    SCHEME=https
else
    SCHEME=http
fi

PING_CMD="${SCHEME}://${LOCAL_IP}:${HC_PORT}/"
echo "pinging ${PING_CMD}"

set +e
while [ true ]; do
    RESULT=$(curl -k -sw "%{http_code}" ${PING_CMD} -o /dev/null)
    echo "Received ${RESULT}"
    if [ ${RESULT} -eq 200 ]; then
      exit 0
    fi
    sleep 1
done
