#!/usr/bin/env bash

# Scripts expects the next environment variables to be set:
# - KSQL_PORT
# - KSQL_USE_QUERY_FILE

# Configure shell.
set -u

# Exit with success on non-interactive (headless) mode.
if [[ "${KSQL_USE_QUERY_FILE}" == 'true' ]]; then
  exit 0
fi

# Check if ksqldb-server API is available on interactive mode.
CURL_STATUS=$( curl -s -o /dev/null -w %{http_code} "http://localhost:${KSQL_PORT}/healthcheck" )
if [[ "${CURL_STATUS}" != '200' ]]; then
  exit 1
fi

# Check if upload-queries success file is created.
if [[ ! -f /home/appuser/upload-queries.succeeded ]]; then
  exit 1
fi

exit 0
