########################################
### function: install kafka
### author: T_T
### create date: 2019-11
### modify date: 2019-11
########################################

## Useage ##
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
  echo "Useage : sh $0 kafka_ip zookeeper:2181 prod/test"
  exit 1
fi

set +e
## ENV ##
source /etc/profile
set -e
pd=$PWD
kafka_ip=$1
zookeeper_connect=$2
environment_type=$3
kafka_version="kafka_2.12-3.2.0"
export kafka_ip=${kafka_ip:-localhost}
export zookeeper_connect=${zookeeper_connect:-zookeeper:2181}
export kafka_log_dir=${kafka_log_dir:-$pd/$kafka_version/kafka-logs}

Xmx_mem="3G"
Xms_mem="3G"
if [ "$environment_type" != "prod" ]; then
  Xmx_mem="512m"
  Xms_mem="512m"
fi

## install kafka ##
if [ -z "$JAVA_HOME" ]; then
  echo "jdk not be installed,please install jdk first!"
  exit 2
fi
tar -xf $pd/$kafka_version.tar.gz --skip-old-files
if [ $? -ne 0 ]; then
  echo "tar $kafka_version.tar.gz failed!"
fi
mkdir -p $kafka_log_dir

## Modify config file ##
sed -i "/^#listeners=/c listeners=PLAINTEXT://$kafka_ip:9092" $pd/$kafka_version/config/server.properties
sed -i "/^zookeeper.connect=/c zookeeper.connect=$zookeeper_connect" $pd/$kafka_version/config/server.properties
sed -i "/^log.dirs=/c log.dirs=$kafka_log_dir" $pd/$kafka_version/config/server.properties

# 修改启动脚本，调大jvm堆栈内存
sed -i -E "s/(export KAFKA_HEAP_OPTS=.*)-Xmx[0-9]+[kmgG]? (.*)-Xms[0-9]+[kmgG]?/\1-Xmx${Xmx_mem} \2-Xms${Xms_mem}/" $pd/$kafka_version/bin/kafka-server-start.sh

## Add kafka user ##
start_kf_user="kafka"
groupadd -f $start_kf_user
IF_START_USER=$(sed -n '/^'${start_kf_user}':/p' /etc/passwd)
if [ -z "${IF_START_USER}" ]; then
  useradd -g $start_kf_user -M -s /sbin/nologin $start_kf_user
fi
chown -R $start_kf_user. $pd

## register systemd ##
#systemctl stop kafka
cat > /usr/lib/systemd/system/kafka.service << EOF
[Unit]
Description=Apache Kafka server (broker)
After=network.target

[Service]
Type=simple
User=$start_kf_user
Group=$start_kf_user
Environment="PATH=$JAVA_HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin"
ExecStart=$pd/$kafka_version/bin/kafka-server-start.sh $pd/$kafka_version/config/server.properties
ExecStop=$pd/$kafka_version/bin/kafka-server-stop.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

## start server ##
systemctl daemon-reload
systemctl restart kafka
systemctl enable kafka
