########################################
### 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 ******"
#    exit 1
#fi

set +e
## ENV ##
source /etc/profile
set -e

pd=$PWD
es_user=$1
es_passwd=$2
if [ -z "$es_passwd" ]; then
  echo "redis es_passwd is empty"
  exit 10
fi

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}

## 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
  # sys_parm改过了
  #[1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
  # 修改并加载内核参数
#  if [[ ! -f /etc/sysctl.d/sysctl_es.conf ]]; then
#    touch /etc/sysctl.d/sysctl_es.conf
#  fi
#
#  cp -f $pd/sysctl_es.conf /etc/sysctl.d/sysctl_es.conf
#  sysctl -p -e /etc/sysctl.d/sysctl_es.conf

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

  # centos中es配置做过修改，arm64时需要把这些修改加上
  exist=$(cat $pd/$es_version/config/elasticsearch.yml | grep -E 'http.cors.enabled\s*:\s*true' | wc -l)
  if [[ ${exist} -eq 0 ]]; then
    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
    cat << EOF >> $pd/$es_version/config/elasticsearch.yml

cluster.name: my-application
network.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "/.*/"
http.port: 9200
indices.fielddata.cache.size: 80%
indices.breaker.fielddata.limit: 80%
indices.breaker.request.limit: 80%
indices.breaker.total.limit: 90%
thread_pool.bulk.queue_size: 1000
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.ml.enabled: false
EOF

  fi

  # 修改jvm.options，调大jvm堆栈内存
  sed -E -i "s/^-Xms[0-9]+[kmg]?$/-Xms8g/" $pd/$es_version/config/jvm.options
  sed -E -i "s/^-Xmx[0-9]+[kmg]?$/-Xmx8g/" $pd/$es_version/config/jvm.options
}

## 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
  count=$($pd/$es_version/bin/elasticsearch-users list | grep "$es_user" | wc -l)
  if [[ $count -eq 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
  echo "Install_es done"
  Modify_config
  echo "Modify_config done"
  Register_systemd
  echo "Register_systemd done"
  Server_options restart
  echo "Server_options done"
  Change_password
  echo "Change_password done"
  Clear_crontab
  echo "Clear_crontab done"
}
main 2>&1 | tee /tmp/install_es.log
