#!/bin/bash

CONFIG_FILE=deploy-config/all.conf
show_env() {
    source scripts/utils.sh
    source scripts/config_get.sh
    source scripts/global_variables.sh
    source scripts/hardware_perfcheck.sh
    echo "==================================="
    echo $NAMESPACE
    echo $WorkNode01
    echo $WorkNode02
    echo $WorkNode03
    echo $aWorkNode01
    echo $aWorkNode02
    echo $aWorkNode03
    echo "==================================="
}

get_deploy_env() {
    namespace=$NAMESPACE
    SSH_PORT=$SSH_PORT
    base_dir=$BASE_DIR
}

get_install_path() {
    find_path=`find / -name "auto_deploy_middleware.sh" -type f | awk -F "auto_deploy_middleware.sh" '{print $1}'`
    install_path="${find_path%%/}"
    #install_path=$(pwd)
    echo "${install_path}"
    cd "${install_path}"
}

deploy_all() {
    cd "${install_path}"/Template/cluster/
    # sed all namespace 加在此处
    sed -i "s/edoc2/$NAMESPACE/g" edoc2_namespace.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" mconfigmap.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" rbac/edoc2-ns-reader-rbac.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" secret/edoc2-secret.yaml
    #sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/minio/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/rabbitmq/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/elasticsearch/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/elasticsearch7.6/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/redis/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/stateful_mysql/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" middleware/haproxy/*.yaml

    #sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/minio/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/rabbitmq/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/elasticsearch/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/elasticsearch7.6/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/redis/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/stateful_mysql/*.yaml
    sed -i "s/.edoc2.svc/.${NAMESPACE}.svc/g" middleware/haproxy/*.yaml

    kubectl apply -f edoc2_namespace.yaml
    sleep 1
    kubectl apply -f mconfigmap.yaml
    sleep 1
    kubectl apply -f rbac/edoc2-ns-reader-rbac.yaml
    sleep 1
    if [ "$Es_Version" == "es6" ]; then
        cd "${install_path}"/Template/cluster/middleware/elasticsearch
        source deploy_es_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $K8S_MASTER_IP01
    fi
    if [ "$Es_Version" == "es7" ]; then
        cd "${install_path}"/Template/cluster/middleware/elasticsearch7.6
        source deploy_es_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $K8S_MASTER_IP01
    fi
    sleep 15
    cd "${install_path}"/Template/cluster/middleware/rabbitmq
    source deploy_rabbitmq_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 150
    cd "${install_path}"/Template/cluster/middleware/redis
    source deploy_redis_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 30
    cd "${install_path}"/Template/cluster/middleware/stateful_mysql
    source deploy_mgr_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 35
    #if [ "${MINIOTYPE}" == "local" ];then
    #    cd "${install_path}"/Template/cluster/middleware/minio
    #    source deploy_minio_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $minio_pv_volume $minio_pv_path
    #    sleep 35
    #fi
    cd "${install_path}"/Template/cluster/middleware/haproxy
    source deploy_proxy_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 35
    cd "${install_path}"/
    \cp -rf ${install_path}/Template/cluster /opt/
}

delete_all() {
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/haproxy
    source deploy_proxy_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 1

    if [ "$Es_Version" == "es6" ]; then
        cd "${install_path}"/Template/cluster/middleware/elasticsearch
        source deploy_es_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    fi
    if [ "$Es_Version" == "es7" ]; then
        cd "${install_path}"/Template/cluster/middleware/elasticsearch7.6
        source deploy_es_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    fi
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/rabbitmq
    source deploy_rabbitmq_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/redis
    source deploy_redis_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 1
    cd "${install_path}"/Template/cluster/middleware/stateful_mysql
    source deploy_mgr_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 1
    #if [ "${MINIOTYPE}" == "local" ];then
    #    cd "${install_path}"/Template/cluster/middleware/minio
    #    source deploy_minio_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $minio_pv_volume $minio_pv_path
    #    sleep 1
    #fi
    cd "${install_path}"/
}

pull_images_info() {
    cd /usr/local/harbor && docker-compose up -d
    sleep 2
    sshpass ssh -p $SSH_PORT root@$WorkNode01 "docker login -u admin -p edoc2edoc2 registry.edoc2.com:5000"
    sshpass ssh -p $SSH_PORT root@$WorkNode02 "docker login -u admin -p edoc2edoc2 registry.edoc2.com:5000"
    sshpass ssh -p $SSH_PORT root@$WorkNode03 "docker login -u admin -p edoc2edoc2 registry.edoc2.com:5000"
    get_install_path
    cd "${install_path}"/Install_Packages/mid_pgk/
    sleep 2
    tar -xf elasticsearch_prod630-v6.7.1-1.tar.xz && docker load -i elasticsearch_prod630-v6.7.1-1.tar
    sleep 2
    docker push registry.edoc2.com:5000/edoc2v5/elasticsearch:prod630-v6.7.1-1
    #tar -xf elasticsearch_prod660-v7.17.4.1.tar.xz && docker load -i elasticsearch_prod660-v7.17.4.1.tar
    #sleep 2
    #docker push registry.edoc2.com:5000/edoc2v5/elasticsearch:prod660-v7.17.4.1
    #sleep 2
    cd "${install_path}"/
    images_list=`cat "${install_path}"/images_requirements.json | grep image | awk -F " " '{print $2}' | grep -v null | awk -F "\"" '{print $2}'`
    #echo "$images"
    for image in $images_list;do
        # es-node01 标签节点
        sshpass ssh -p $SSH_PORT root@$WorkNode01 "docker pull $image"

        # es-node02 标签节点
        sshpass ssh -p $SSH_PORT root@$WorkNode02 "docker pull $image"

        # es-node03 标签节点
        sshpass ssh -p $SSH_PORT root@$WorkNode03 "docker pull $image"
    done
    sleep 5
    echo "##### 清理log4jar残存 ###########################"
    get_install_path
    source "${install_path}"/scripts/clean_log4jar.sh
    #cd /usr/local/harbor && docker-compose down
}

create_main_configmap() {
    cat << EOF > ${install_path}/Template/cluster/mconfigmap.yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: menvfile
  namespace: $NAMESPACE
data:
  CONTAINER_PLATFORM: "kubernetes"
  LOGGER_MINCALLTIMESPAN: "1000"
  ContainerContent: "https://$K8S_MASTER_LB_IP:8443"
  PUBLISH_EXTERNAL_ADDRESS: "http://localhost/"
  ContainerType: "0"
  PRODUCTION: "edoc2"
  ES_JAVA_OPTS: $ES_JAVA_OPTS
EOF
# CLIENTSYNC: false
    sed -i "s#g-Xms#g -Xms#g" ${install_path}/Template/cluster/mconfigmap.yaml
}

auto_cluster() {
    cat /etc/rc.d/rc.local | grep calicoctl
    calico_status=$?
    echo $calico_status
    if [ ${calico_status} == "1" ];then
        #echo "cd /usr/local/harbor && docker-compose up -d" >> /root/.bashrc
        echo "sleep 2 && calicoctl patch node $K8S_NODE01 --patch='{\"spec\":{\"bgp\": {\"ipv4Address\": \"$K8S_NODE_IP01/24\"}}}' --allow-version-mismatch" >> /etc/rc.d/rc.local
        echo "sleep 2 && calicoctl patch node $K8S_NODE01 --patch='{\"spec\":{\"bgp\": {\"ipv4Address\": \"$K8S_NODE_IP01/24\"}}}' --allow-version-mismatch" >> /etc/profile
        #echo "exportfs -rv" >> /etc/profile
        echo "systemctl restart rpcbind.service" >> /etc/profile
        echo "systemctl restart nfs.service" >> /etc/profile
        #echo "systemctl restart nfs" >> /etc/profile
    else
        sleep 1
    fi
    cat /etc/crontab | grep calicoctl
    calico_crontab_status=$?
    echo $calico_crontab_status
    if [ ${calico_crontab_status} == "1" ];then
        echo "*/1 * * * * root calicoctl patch node $K8S_NODE01 --patch='{\"spec\":{\"bgp\": {\"ipv4Address\": \"$K8S_NODE_IP01/24\"}}}' --allow-version-mismatch" >> /etc/crontab
    else
        sleep 1
    fi
}

cat <<eof 
**************************************
** all operation start/stop/restart **
**************************************
eof

sleep 1
show_env
get_deploy_env
Action=$1
Es_Version="es6"

if [ -z "$Es_Version" ]; then
    echo “****************************************************************************************************************************”
    echo "Error: Elasticsearch 版本参数不能为空(ES版本选择)！ "
    echo "请执行 source auto_deploy_middleware.sh start es6 或者 source auto_deploy_middleware.sh start es7"
    echo "（es6支持ecm6.6以下版本，es7支持ecm6.6及以上版本, ecm产线版本对es版本有兼容依赖性，请确认你需要部署产线对应的es版本！！！）"
    echo “****************************************************************************************************************************”
    exit 1
fi

if [ "$Es_Version" != "es7" ] && [ "$Es_Version" != "es6" ]; then
    echo “****************************************************************************************************************************”
    echo "Error: Elasticsearch 版本参数错误(ES版本选择)！"
    echo "请执行 source auto_deploy_middleware.sh start es6 或者 source auto_deploy_middleware.sh start es7"
    echo "（es6支持ecm6.6以下版本，es7支持ecm6.6及以上版本, ecm产线版本对es版本有兼容依赖性，请确认你需要部署产线对应的es版本！！！）"
    exit 1
    echo “****************************************************************************************************************************”
fi

echo “****************************************************************************************************************************”
if [ "$Es_Version" == "es6" ]; then
    echo "当前ES版本为："${Es_Version}
    echo "适配兼容的Ecm版本小于 < ecm-v6.6.0.0"
fi
if [ "$Es_Version" == "es7" ]; then
    echo "当前ES版本为："${Es_Version}
    echo "适配兼容的Ecm版本大于等于 >= ecm-v6.6.0.0"
fi
echo “****************************************************************************************************************************”

# get_deploy_env
case $Action in 
    1|start|START)
        get_install_path
        sleep 1
        hardware_perfcheck
        pull_images_info
        sleep 1
        echo "begin deploy ecm ........."
        create_main_configmap
        sleep 5
        auto_cluster
        sleep 5
        deploy_all
        sleep 5
        ;;
    2|stop|STOP)
        get_install_path
        echo "begin stop ecm ..........."
        sleep 3
        delete_all 
        sleep 5
        ;;
    3|restart|RESTART)
        get_install_path
        echo "begin restart ecm ........"
        sleep 3
        delete_all
        sleep 5
        pull_images_info
        sleep 1
        echo "begin deploy ecm ........."
        create_main_configmap
        sleep 5
        auto_cluster
        sleep 5
        deploy_all
        ;;
    *)
        echo "输入操作不存在 .........."
        #exit;
esac
