#!/bin/bash

set -e

#rhoover: it's important to create new directory because
# the OS may create a lost+found directory when mounting a
# block device which can cause the application to fail
DATA_DIR="/data/control-center"
mkdir -p $DATA_DIR

#Wait for ZooKeeper servers to be launched
cpsvc zookeeper client-metadata-wait
#Wait for Kafka brokers to be launched
cpsvc kafka client-metadata-wait

ZK_CONNECT=$(cpsvc zookeeper client-config)
BOOSTRAP_SERSVERS=$(cpsvc kafka client-bootstrap-servers)

: ${CONTROL_CENTER_ID:=0}
: ${CONTROL_CENTER_MONITORING_TOPIC_NAME:="_confluent-monitoring"}
: ${CONTROL_CENTER_NUM_THREADS:=4}
: ${CONTROL_CENTER_MONITORING_TOPIC_PARTITIONS:=4}
: ${CONTROL_CENTER_MONITORING_TOPIC_REPLICATION:=3}
: ${CONTROL_CENTER_MONITORING_TOPIC_RETENTION_MS:=259200000}
: ${CONTROL_CENTER_INTERNAL_TOPICS_PARTITIONS:=4}
: ${CONTROL_CENTER_INTERNAL_TOPICS_REPLICATION:=3}
: ${CONTROL_CENTER_INTERNAL_TOPICS_RETENTION_MS:=86400000}

C3_CONFIG_FILE="/opt/control-center/etc/confluent-control-center/control-center.properties"
cat <<- EOF > $C3_CONFIG_FILE
    confluent.controlcenter.id=${CONTROL_CENTER_ID}
    zookeeper.connect=${ZK_CONNECT}
    bootstrap.servers=${BOOSTRAP_SERSVERS}
    confluent.controlcenter.data.dir=${DATA_DIR}
    confluent.controlcenter.internal.topics.partitions=${CONTROL_CENTER_INTERNAL_TOPICS_PARTITIONS}
    confluent.controlcenter.internal.topics.replication=${CONTROL_CENTER_INTERNAL_TOPICS_REPLICATION}
    confluent.controlcenter.internal.topics.retention.ms=${CONTROL_CENTER_INTERNAL_TOPICS_RETENTION_MS}
    confluent.monitoring.interceptor.topic=${CONTROL_CENTER_MONITORING_TOPIC_NAME}
    confluent.monitoring.interceptor.topic.partitions=${CONTROL_CENTER_MONITORING_TOPIC_PARTITIONS}
    confluent.monitoring.interceptor.topic.replication=${CONTROL_CENTER_MONITORING_TOPIC_REPLICATION}
    confluent.monitoring.interceptor.topic.retention.ms=${CONTROL_CENTER_MONITORING_TOPIC_RETENTION_MS}
    confluent.controlcenter.streams.num.stream.threads=${CONTROL_CENTER_NUM_THREADS}
EOF

echo "$(cat $C3_CONFIG_FILE)"

#Wait for ZK ensemble
cpsvc zookeeper client-up-wait
#Wait for Kafka cluster
cpsvc kafka client-up-wait

echo "Starting Control Center"
exec /opt/control-center/bin/control-center-start $C3_CONFIG_FILE
