#!/usr/bin/env bash
#
# Copyright 2016-2017 Confluent Inc.
#

set -o nounset \
    -o errexit \
    -o verbose

echo "===> Check that log dirs are writable ..."
# You need to set KAFKA_LOG_DIRS to be a child of the mount point
# We create the data directory here if necessary to avoid the issue
# where a mounted volume has a lost+found directory
# which makes the broker choke thinking it's a Kafka topic
export KAFKA_LOG_DIRS=$(grep "log.dirs" ${KAFKA_CONFIG_DIR}/kafka.properties | cut -d '=' -f 2)
mkdir -p "$KAFKA_LOG_DIRS" && chmod ag+w "$KAFKA_LOG_DIRS"
dub path "$KAFKA_LOG_DIRS" writable

echo "===> Check that log4j dir is writable ..."
mkdir -p "$KAFKA_LOG4J_DIR" && chmod ag+w "$KAFKA_LOG4J_DIR"
dub path "$KAFKA_LOG4J_DIR" writable

kraft_cluster_id=$(grep "^#KRaftClusterId=" ${KAFKA_CONFIG_DIR}/kafka.properties | cut -d '=' -f 2)
export KAFKA_ZOOKEEPER_CONNECT=$(grep "zookeeper.connect" ${KAFKA_CONFIG_DIR}/kafka.properties | cut -d '=' -f 2)
if [ -z "$kraft_cluster_id" -a -z "$KAFKA_ZOOKEEPER_CONNECT" ]; then
    echo "Fail: No zookeeper.connect and no #KRaftClusterId in ${KAFKA_CONFIG_DIR}/kafka.properties"
    exit 1
fi
if [ ! -z "$kraft_cluster_id" ]; then
    echo "===> Run kafka-storage tool ..."
    /opt/confluent/bin/kafka-storage.sh format --ignore-formatted --config ${KAFKA_CONFIG_DIR}/kafka.properties --cluster-id=$kraft_cluster_id || exit $?
fi
if [ ! -z "$KAFKA_ZOOKEEPER_CONNECT" ]; then
    echo "===> Check if Zookeeper is healthy ..."
    cub zk-ready "$KAFKA_ZOOKEEPER_CONNECT" "${KAFKA_CUB_ZK_TIMEOUT:-40}" || exit $?
fi
