#!/usr/bin/env bash

# Script expects the next environment variables to be set:
# - Environment
# - KSQL_PORT

# Configure shell.
set -u

# Set global success flag.
UPLOAD_SUCCESSFUL='true'

# Set global debug flag.
UPLOAD_DEBUG="${UPLOAD_QUERIES_DEBUG:-false}"

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

# Query file upload function.
uploadQuery() {
  local QUERY_FILE="$1"

  # Upload query file.
  log "Uploading ${QUERY_FILE} query file"

  # Bash do not handle unicode chars properly
  # so '/tmp/curl_payload.json' the file used to mitigate this
  echo -n '{"ksql": "' > /tmp/curl_payload.json \
    && cat ${QUERY_FILE} | sed 's|^[[:space:]]*||;\|^--.*|d;s|[[:space:]]*--.*||g;s|"|\\"|g' | expand -t1 | tr '\n' ' ' | sed 's|  *| |g' >> /tmp/curl_payload.json \
    && echo -n '"}' >> /tmp/curl_payload.json

  if [[ "${UPLOAD_DEBUG}" == 'true' ]]; then
    local CURL_PAYLOAD=`cat /tmp/curl_payload.json`
    log "Query request payload: $( echo "${CURL_PAYLOAD}" | tr '\n' ' ' | sed 's|  *| |g' )"
  fi

  CURL_STATUS=$( curl -s -o /tmp/upload-queries.response -w %{http_code} -XPOST \
                  -H 'Accept: application/vnd.ksql.v1+json, application/json' \
                  -H 'Content-Type: application/vnd.ksql.v1+json' \
                  -d @/tmp/curl_payload.json \
                  "http://localhost:${KSQL_PORT}/ksql" )

  if [[ "${CURL_STATUS}" != '200' ]]; then
    # This should not be wrapped into log() since JSON fields are automatically parsed in DataDog
    cat /tmp/upload-queries.response \
      | jq --arg query_file "${QUERY_FILE}" '.query_file |= $query_file' \
      | jq --arg ksql "$(cat ${QUERY_FILE})" '.ksql |= $ksql' \
      | jq -c --arg curl_status "${CURL_STATUS}" '.curl_status |= $curl_status'
    return 1
  fi

  log "Upload has succeeded for ${QUERY_FILE} query file"

  return 0
}

# Wait for ksqldb-server initialization.
log 'Waiting for ksqldb-server to start...'
while [[ true ]]; do
  CURL_STATUS=$( curl -s -o /dev/null -w %{http_code} "http://localhost:${KSQL_PORT}/healthcheck" )
  if [[ "${CURL_STATUS}" == '200' ]]; then
    log 'Ksqldb-server has started'
    break
  fi
  log "Ksqldb-server listener HTTP state: ${CURL_STATUS}. Waiting for 200..."
  sleep 5
done

# Process query files
# Ignore shared queries in local environment
if [[ "${Environment}" != 'local' ]]; then
  log 'Processing shared query files'
  for QUERY_FILE in $( find /home/appuser/queries/shared -maxdepth 2 -type f -name '*.ksql' | sort ); do
    uploadQuery "${QUERY_FILE}"
    if [[ $? -ne 0 ]]; then
      UPLOAD_SUCCESSFUL='false'
      continue
    fi
  done
fi

if [[ -d "/home/appuser/queries/${Environment}" ]]; then
  log "Processing ${Environment} environment query files"
  for QUERY_FILE in $( find "/home/appuser/queries/${Environment}" -maxdepth 2 -type f -name '*.ksql' | sort ); do
    uploadQuery "${QUERY_FILE}"
    if [[ $? -ne 0 ]]; then
      UPLOAD_SUCCESSFUL='false'
      continue
    fi
  done
fi

if [[ "${UPLOAD_SUCCESSFUL}" != 'true' ]]; then
  log 'Query files upload has finished with errors. Check the above logs to find the details.'
  exit 1
fi

# Create the success flag file for the healthcheck script.
log 'Query files upload has finished successfully'
touch /home/appuser/upload-queries.succeeded
