######################################################################
#### function: install zookeeper
####author:danial_chen
####create date:2019-11-07
####modify date:2019-11-07
######################################################################
#/bin/bash
#useage: sh installzk.sh "zk_ip1 zk_ip2 zk_ip3" zkserver_id
#eg. sh installzk.sh "192.168.1.11 192.168.1.12 191.168.1.13" 2
if [ -z "$1" ] || [ -z "$2" ];then
    echo "Useage : sh $0 "zk_ip1 zk_ip2 zk_ip3" zkserver_id"
	echo "Default: sh $0 "192.168.1.11 192.168.1.12 191.168.1.13" 2"
    exit 1
fi

## ENV ##
source /etc/profile
pd=$PWD
zookeeper_ip=($1)
zkserver_id=$2
zookeeper_version="zookeeper-3.5.9"
export dataDir=${dataDir:-$pd/data/zk_2181/data}
export dataLogDir=${dataLogDir:-$pd/data/zk_2181/logs}

## install zookeeper ##
if [ -z "$JAVA_HOME" ];then
    echo "jdk not be installed,please install jdk first!"
    exit 2
fi
tar -zxf $pd/$zookeeper_version.tar.gz
chmod -R 755 $pd/$zookeeper_version
if [ $? -ne 0 ];then
    echo "tar $zookeeper_version.tar.gz failed!"
fi
mkdir -p $dataDir
mkdir -p $dataLogDir

## Modify config file ## 
sed -i "/^dataDir=/c dataDir=$dataDir" $pd/$zookeeper_version/conf/zoo.cfg
sed -i "/^dataLogDir=/c dataLogDir=$dataLogDir" $pd/$zookeeper_version/conf/zoo.cfg
echo ' ' >> $pd/$zookeeper_version/conf/zoo.cfg
echo "admin.serverPort=2388" >> $pd/$zookeeper_version/conf/zoo.cfg
echo 'maxClientCnxns=600' >> $pd/$zookeeper_version/conf/zoo.cfg
echo 'autopurge.snapRetainCount=3' >> $pd/$zookeeper_version/conf/zoo.cfg
echo 'autopurge.purgeInterval=1' >> $pd/$zookeeper_version/conf/zoo.cfg




if [ ${#zookeeper_ip[@]} -gt 1 ];then
echo $zkserver_id > $dataDir/myid
for((i=${#zookeeper_ip[@]};i>0;i--))
do
    b=$((${i} - 1))
    sed -i "/^clientPort/a server.${i}=${zookeeper_ip[$b]}:2888:3888" $pd/$zookeeper_version/conf/zoo.cfg
done
fi

## Add system environment variable ##
export ZK_HOME=$pd/$zookeeper_version
echo "export ZK_HOME=$pd/$zookeeper_version">>/etc/profile
echo "PATH=\$ZK_HOME/bin:\$PATH:\$HOME/bin">>/etc/profile
source /etc/profile

## register systemd ##
systemctl stop zookeeper.service
cat > /usr/lib/systemd/system/zookeeper.service <<EOF
[Unit]
Description=zookeeper
After=syslog.target network.target

[Service]
Type=forking
Environment=ZOO_LOG_DIR=$dataLogDir
Environment=ZOO_LOG4J_PROP=WARN,ROLLINGFILE
Environment="PATH=$JAVA_HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin"
ExecStart=$pd/$zookeeper_version/bin/zkServer.sh start
ExecStop=$pd/$zookeeper_version/bin/zkServer.sh stop

[Install]
WantedBy=multi-user.target
EOF

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

echo "install zookeeper success!"
