#!/usr/bin/env bash

# Configure shell.
set -m

# User-friendly print wrapper.
log() {
  printf '[%s] [%s] %s\n' "${0##*/}" "$( date '+%Y-%m-%dT%H:%M:%S' )" "${@}"
}

# Configure default environment variables.
export KSQL_KSQL_ADVERTISED_LISTENER="http://localhost:${KSQL_PORT}"

# Configure unique service ID per application cluster.
export KSQL_KSQL_SERVICE_ID="kafka_ksqldb_${KSQL_GROUP_UNIQUE_IDENTIFIER}"

log 'Configuring truststore location'
JAVA_HOME=$(java -XshowSettings:properties -version 2>&1 > /dev/null | grep -i java.home | awk '{print $3}')
CACERT_FILE=$(find "${JAVA_HOME}" -type f -name "cacerts" | awk 'NR==1{print $1}')
export KSQL_SSL_TRUSTSTORE_LOCATION="${CACERT_FILE}"
export KSQL_SSL_TRUSTSTORE_PASSWORD="changeit"
export KSQL_SCHEMA_REGISTRY_SSL_TRUSTSTORE_LOCATION="${CACERT_FILE}"
export KSQL_SCHEMA_REGISTRY_SSL_TRUSTSTORE_PASSWORD="changeit"

# Assume this is a Fargate task. Find the private IP address without installing additional packages.
if [[ "${Environment}" != 'local' ]]; then
  log 'Setting proper hostname from Fargate metadata'
  DNS_NAME=$(curl -s ${ECS_CONTAINER_METADATA_URI_V4}/task | jq -r '.Containers[0].Networks[0].PrivateDNSName')
  log "Task DNS name is ${DNS_NAME}"
  export KSQL_KSQL_ADVERTISED_LISTENER="http://${DNS_NAME}:${KSQL_PORT}"
fi

# Source the dotenv file volume in the container if running locally.
# Alter if you change the path where .env is mounted.
if [[ "${Environment}" == 'local' ]]; then
  if [ -f /etc/kafka-connect/connector_config.properties ]; then
    log 'Sourcing local environment variables'
    . /etc/kafka-connect/connector_config.properties
  fi
fi

# Actions for interactive/non-interactive mode.
if [[ "${KSQL_USE_QUERY_FILE}" == 'true' ]]; then
  log 'Non-interactive (headless) mode selected.'
  log 'Merging all KSQL queries together.'

  touch /home/appuser/queries.ksql

  for QUERY_FILE in $( find /home/appuser/queries/shared -maxdepth 1 -type f -name '*.ksql' | sort ); do
    cat "${QUERY_FILE}" >> /home/appuser/queries.ksql
  done

  if [[ -d "/home/appuser/queries/${Environment}" ]]; then
    for QUERY_FILE in $( find "/home/appuser/queries/${Environment}" -maxdepth 1 -type f -name '*.ksql' | sort ); do
      cat "${QUERY_FILE}" >> /home/appuser/queries.ksql
    done
  fi

  export KSQL_KSQL_QUERIES_FILE='/home/appuser/queries.ksql'

  log 'Queries file content:'
  cat /home/appuser/queries.ksql
else
  log 'Interactive mode selected.'
  log 'Launching upload-queries.sh'
  /usr/local/bin/upload-queries.sh &
fi

# Launch the base container entry point.
log 'Launching ksqldb-server entrypoint'
exec '/usr/bin/docker/run'
