#!/bin/bash

if [ "$WAIT_FOR_KAFKA" != "1" ]; then
  echo "Starting without checking for Kafka availability"
  exit 0
fi

max_timeout=32


IS_TEMP=0

if [ -z "$COMMAND_CONFIG_FILE_PATH" ]; then
    COMMAND_CONFIG_FILE_PATH="$(mktemp)"
    IS_TEMP=1
fi

if [ ! -f "$COMMAND_CONFIG_FILE_PATH" ] || [ $IS_TEMP = 1 ]; then
    while IFS='=' read -r -d '' n v; do
        if [[ "$n" == "CONNECT_"* ]]; then
            name="${n/CONNECT_/""}" # remove first "CONNECT_"
            name="${name,,}" # lower case
            name="${name//_/"."}" # replace all '_' with '.'
            echo "$name=$v" >> ${COMMAND_CONFIG_FILE_PATH}
        fi
    done < <(env -0)
fi

# Check if variables exist
if [ -z "$CONNECT_BOOTSTRAP_SERVERS" ]; then
    echo "CONNECT_BOOTSTRAP_SERVERS is not defined"
else
    KAFKA_BROKERS=${KAFKA_BROKERS:-3}

    tries=10
    timeout=1
    while true; do
        KAFKA_CHECK=$(kafka-broker-api-versions --bootstrap-server "$CONNECT_BOOTSTRAP_SERVERS" --command-config "${COMMAND_CONFIG_FILE_PATH}" | grep "(id: " | wc -l)

        if [ "$KAFKA_CHECK" -ge "$KAFKA_BROKERS" ]; then
            echo "Kafka brokers available."
            break
        fi

        tries=$((tries - 1))
        if [ ${tries} -eq 0 ]; then
            echo "FAILED: KAFKA BROKERs NOT READY."
            exit 5
        fi
        echo "Expected $KAFKA_BROKERS brokers but found only $KAFKA_CHECK. Waiting $timeout second before retrying ..."
        sleep ${timeout}
        if [ ${timeout} -lt ${max_timeout} ]; then
            timeout=$((timeout * 2))
        fi
    done

    echo "Kafka is available."
fi

if [ -z "$CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL" ]; then
    echo "CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL is not defined"
else
    tries=10
    timeout=1
    while true; do
        if wget --spider -q "${CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL}/subjects" 2>/dev/null; then
            echo "Schema registry available."
            break
        fi
        tries=$((tries - 1))
        if [ $tries -eq 0 ]; then
            echo "FAILED TO REACH SCHEMA REGISTRY."
            exit 6
        fi
        echo "Failed to reach schema registry. Retrying in ${timeout} seconds."
        sleep ${timeout}
        if [ ${timeout} -lt ${max_timeout} ]; then
            timeout=$((timeout * 2))
        fi
    done

    echo "Schema registry is available."
fi

if [ $IS_TEMP = 1 ]; then
    /bin/rm -f "$COMMAND_CONFIG_FILE_PATH"
fi
