########################################
### function: install elasticsearch, this version of es has authentication
### author: T_T
### create date: 2019-11
### modify date: 2019-11
########################################

## Useage ##
#if [ -z "$1" ];then
#    echo "Useage : sh $0 es_user {es_passwd}"
     echo "Default: sh $0 elastic Cosmic@2020"
#    exit 1
#fi

## ENV ##
source /etc/profile
pd=$PWD
es_user=$1
es_passwd=$2
start_es_user=$3
es_version="elasticsearch-6.8.18"
export start_es_user=${start_es_user:-elsearch}
export es_user=${es_user:-elastic}
export es_passwd=${es_passwd:-Kingdee@2020}

## install elasticsearch ##
Install_es(){
rpm -Uvh $pd/*.rpm --nodeps --force 
if [ -z "$JAVA_HOME" ];then
    echo "jdk not be installed,please install jdk first!"
    exit 2
fi 
groupadd -f $start_es_user
IF_START_USER=`sed -n '/^'${start_es_user}':/p' /etc/passwd`
if [ -z "${IF_START_USER}" ];then
    useradd -g $start_es_user -d /home/$start_es_user $start_es_user 
fi
tar -xzf $pd/$es_version.tar.gz
chown -R $start_es_user. $pd/
}

## Modify config file ## 
Modify_config(){
sed -i "/^path.data:/c path.data: $pd/esdata" $pd/$es_version/config/elasticsearch.yml
sed -i "/^path.logs:/c path.logs: $pd/esdata/logs" $pd/$es_version/config/elasticsearch.yml
mkdir -p $pd/esdata/logs
#[1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
MAX_MAP_COUNT=`sed -n '/vm.max_map_count/p' /etc/sysctl.conf`
if [ -z "$MAX_MAP_COUNT" ];then
    echo "vm.max_map_count = 655360" >> /etc/sysctl.conf
    sysctl -p 
else
    sed -i "/^vm.max_map_count/c vm.max_map_count = 655360" /etc/sysctl.conf
    sysctl -p 
fi

chown -R ${start_es_user}.  $pd/esdata $pd/$es_version/
}


## register systemd ##
Register_systemd(){
systemctl stop es 
cat > /usr/lib/systemd/system/es.service << EOF
[Unit]
Description=elasticsearch server (broker)
After=syslog.target network.target 

[Service] 
User=$start_es_user
Group=$start_es_user
Environment="JAVA_HOME=$JAVA_HOME"
Environment="PATH=$JAVA_HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin"
Environment=ES_HOME=$pd/$es_version
Environment=ES_PATH_CONF=$pd/$es_version/config 
Environment=PID_DIR=/home/$start_es_user
ExecStart=$pd/$es_version/bin/elasticsearch -p \${PID_DIR}/elasticsearch.pid
LimitNOFILE=65536
LimitNPROC=4096
LimitAS=infinity
LimitFSIZE=infinity
TimeoutStopSec=0
KillSignal=SIGTERM
KillMode=process
SendSIGKILL=no
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
EOF
}

## server options ##
Server_options(){
systemctl daemon-reload
systemctl $1 es
systemctl enable es
}
## change password ##
Change_password(){
times=1
while [ $times -lt 100 ]
do
esps=`netstat -ntpl|grep 9200|wc -l`
if [ $esps -eq 1 ];then
    break;
fi
sleep 5
let "times = $times + 1 "
done
# add superuser to change $es_user's password
$pd/$es_version/bin/elasticsearch-users list|grep -w "$es_user" &>/dev/null
if [ $? -ne 0 ] && [ "$es_user" != "elastic" ];then
    $pd/$es_version/bin/elasticsearch-users useradd "${es_user}" -p "${es_passwd}" -r superuser
else
    $pd/$es_version/bin/elasticsearch-users useradd kdadmin -p Kdes_2019 -r superuser 
    sleep 5
    curl -u kdadmin:Kdes_2019 -XPUT 'http://127.0.0.1:9200/_xpack/security/user/'$es_user'/_password?pretty' -H 'Content-Type: application/json' -d '{ "password" : "'$es_passwd'" }'
fi
}

## auto clear es's log ##
Clear_crontab(){

cat >  /home/${start_es_user}/autoclear.sh << EOF
#!/bin/bash
es_user=${es_user}
es_password="${es_passwd}"
retain_time=\`date +%Y%m%d -d "7 days ago"\`

function delete_indices() {
time_num=\`echo \$1|sed 's/-//g'\`
if [ \${time_num} -lt \${retain_time} ];then
   curl -X DELETE http://127.0.0.1:9200/*\$1 -u \${es_user}:\${es_password}
fi
}
curl -XGET http://127.0.0.1:9200/_cat/indices -u \${es_user}:\${es_password} |awk '{print \$3}' |grep '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}'|awk '{print substr(\$0,length(\$0)-9)}'|sort -n|uniq|while read line; do delete_indices \$line; done
EOF

echo "0 1 * * *  sh /home/${start_es_user}/autoclear.sh"  > /var/spool/cron/${start_es_user}
chown -R ${start_es_user}.  /var/spool/cron/${start_es_user}  /home/${start_es_user}
}

main(){
Install_es
Modify_config
Register_systemd
Server_options start
Change_password
Clear_crontab
}
main >/tmp/install_es.log 2>&1
