########################################
### function: change password of es & logstash
### author: T_T
### create date: 2019-12
### modify date: 2019-12
########################################


## Useage ##
if [ -z "$3" ];then
    echo -e "Useage : \033[32m sh $0 es_user es_passwd old_es_passwd \033[0m,if you forgot old_es_passwd,you can execute:\033[31m sh $0 es_user es_passwd forgot \033[0m"
    exit 1
fi

## ENV ##
es_user=$1
es_passwd=$2
old_es_passwd=$3
es_version="elasticsearch-6.8.18"
logstash_version="logstash-6.8.18"
pd=$PWD


Change_ES_Password(){
if [ "${old_es_passwd}" == "forgot" ];then
    $pd/elastiasearch/$es_version/bin/elasticsearch-users useradd kdadmin -p Kdes_2019 -r superuser &>/dev/null
    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'" }' 
    [ $? -ne 0 ] && echo "change password of elastiasearch failed! please see logs in $pd/change_elk_password.log"  
else
    curl -u ${es_user}:${old_es_passwd} -XPUT 'http://127.0.0.1:9200/_xpack/security/user/'$es_user'/_password?pretty' -H 'Content-Type: application/json' -d '{ "password" : "'$es_passwd'" }'
	[ $? -ne 0 ] && echo "change password of elastiasearch failed! please see logs in $pd/change_elk_password.log" 
fi	
}

Change_Logstash_Password(){
cat $pd/logstash/$logstash_version/config/javalog.conf |grep  -A 10 elasticsearch |grep user &>/dev/null
if [ $? -eq 0 ];then
    sed -i "/user/c \ \ \ \ \ \ \ \ \ \ \ \ user => \"${es_user}\"" $pd/logstash/$logstash_version/config/javalog.conf
    sed -i "/password/c \ \ \ \ \ \ \ \ \ \ \ \ password => \"${es_passwd}\"" $pd/logstash/$logstash_version/config/javalog.conf
else
	sed -i "/index/a \ \ \ \ \ \ \ \ \ \ \ \ password => \"${es_passwd}\"" $pd/logstash/$logstash_version/config/javalog.conf
    sed -i "/index/a \ \ \ \ \ \ \ \ \ \ \ \ user => \"${es_user}\"" $pd/logstash/$logstash_version/conf/javalog.conf
fi
#systemctl restart logstash
echo "change elasticsearch password in logstash server successfully,please restart logstash server!"
}

main(){
Change_ES_Password
Change_Logstash_Password
}
main
