#!/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 $ES_PV_VOLUME
    echo $ES_PV_PATH
    echo $ES_BACKUP_VOLUME
    echo $ES_BACKUP_PATH
    echo $MQ_PV_VOLUME
    echo $MQ_PV_PATH
    echo $REDIS_PV_VOLUME             
    echo $REDIS_PV_PATH
    echo $BASE_DIR
    echo $MINIO_PV_VOLUME
    echo $MINIO_PV_PATH
    echo $SSH_PORT
    echo ${RANCHER_STATUS}
    echo $MINIOTYPE
    echo $ES_JAVA_OPTS
    echo $STORAGE_MODE
    echo $K8S_MASTER_LB_IP
    echo $WF
    echo $WEBOFFIC
    echo "==================================="
}

get_deploy_env() {
    namespace=$NAMESPACE
    SSH_PORT=$SSH_PORT
    es_pv_volume=$ES_PV_VOLUME
    es_pv_path=$ES_PV_PATH
    es_backup_volume=$ES_BACKUP_VOLUME
    es_backup_path=$ES_BACKUP_PATH
    rabbit_pv_volume=$MQ_PV_VOLUME
    rabbit_pv_path=$MQ_PV_PATH
    redis_pv_volume=$REDIS_PV_VOLUME
    redis_pv_path=$REDIS_PV_PATH
    base_dir=$BASE_DIR
    mgr_pv_volume=$MGR_PV_VOLUME
    mgr_backup_volume=$MGR_BACKUP_VOLUME
    minio_pv_volume=$MINIO_PV_VOLUME
    minio_pv_path=$MINIO_PV_PATH
}

get_install_path() {
    find_path=`find / -name "auto_deploy_edoc2.sh" -type f | awk -F "auto_deploy_edoc2.sh" '{print $1}'`
    install_path="${find_path%%/}"
    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" configmap.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" app/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" apm/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" inbiz/*.yaml
    sed -i "s/namespace: edoc2/namespace: $NAMESPACE/g" searchengine/*.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/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/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
    kubectl apply -f configmap.yaml
    #kubectl apply -f nginx-configmap.yaml
    kubectl apply -f rbac/edoc2-ns-reader-rbac.yaml
    sleep 1
    cd "${install_path}"/Template/cluster/middleware/elasticsearch
    source deploy_es_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $es_pv_volume $es_pv_path $es_backup_volume $es_backup_path $K8S_MASTER_IP01
    sleep 15
    cd "${install_path}"/Template/cluster/middleware/rabbitmq
    source deploy_rabbitmq_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $rabbit_pv_volume $rabbit_pv_path
    sleep 150
    cd "${install_path}"/Template/cluster/middleware/redis
    source deploy_redis_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $redis_pv_volume $redis_pv_path
    sleep 30
    cd "${install_path}"/Template/cluster/middleware/stateful_mysql
    source deploy_mgr_env.sh start $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $base_dir $mgr_pv_volume $mgr_backup_volume
    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}"/Template/cluster/app
    source app_deploy_env.sh start $namespace $aWorkNode01 $aWorkNode02 $aWorkNode03 $SSH_PORT
    sleep 15
    cd "${install_path}"/Template/cluster/inbiz
    source inbiz_deploy_env.sh start $namespace $aWorkNode01 $aWorkNode02 $aWorkNode03 $SSH_PORT
    sleep 15
    cd "${install_path}"/Template/cluster/searchengine
    source deploy_searchengine_env.sh start $namespace $aWorkNode01 $aWorkNode02 $aWorkNode03
    sleep 5
    cd "${install_path}"/
    \cp -rf ${install_path}/Template/cluster /opt/
}

delete_all() {
    cd "${install_path}"/Template/cluster/app
    source app_deploy_env.sh stop $namespace $aWorkNode01 $aWorkNode02 $aWorkNode03 $SSH_PORT
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/haproxy
    source deploy_proxy_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT
    sleep 1
    cd "${install_path}"/Template/cluster/middleware/elasticsearch
    source deploy_es_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $es_pv_volume $es_pv_path $es_backup_volume $es_backup_path
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/rabbitmq
    source deploy_rabbitmq_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $rabbit_pv_volume $rabbit_pv_path
    sleep 2
    cd "${install_path}"/Template/cluster/middleware/redis
    source deploy_redis_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $redis_pv_volume $redis_pv_path
    sleep 1
    cd "${install_path}"/Template/cluster/middleware/stateful_mysql
    source deploy_mgr_env.sh stop $namespace $WorkNode01 $WorkNode02 $WorkNode03 $SSH_PORT $base_dir
    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}"/
}

create_apm() {
    cd "${install_path}"/Template/cluster/apm
    sed -i "s/192.168.251.252/$K8S_MASTER_LB_IP/g" *.yaml
    sleep 1
    source deploy_apm.sh start 
}

delete_apm() {
    cd "${install_path}"/Template/cluster/apm
    source deploy_apm.sh stop
}

auto_backup_logs_start() {
    cd "${install_path}"/
    source auto_backup_logs.sh start
}

auto_backup_logs_stop() {
    cd "${install_path}"/
    source auto_backup_logs.sh stop
}

delete_error_rancher() {
    cd "${install_path}"/
    if [ -f "${install_path}/pids/rancher.pid" ];then
        kill -9 `cat "${install_path}"/pids/rancher.pid`
        sleep 1
    fi
    source delete_rancher_error.sh &
    jobs_process=`jobs -l | grep -v grep | awk -F " " '{print $2}'`
    echo $jobs_process
    echo $jobs_process > "${install_path}"/pids/rancher.pid
}

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}"/
    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() {
    if [ $STORAGE_MODE == "s3" ];then
        storageplatform="1000"
    elif [ $STORAGE_MODE == "minio" ];then
        storageplatform="1000"
    elif [ $STORAGE_MODE == "local" ];then
        storageplatform="0"
    elif [ $STORAGE_MODE == "nas" ];then
        storageplatform="0"
    elif [ $STORAGE_MODE == "oss" ];then
        storageplatform="4"
    elif [ $STORAGE_MODE == "ceph" ];then
        storageplatform="2"
    elif [ $STORAGE_MODE == "swift" ];then
        storageplatform="3"
    fi

cat << EOF > ${install_path}/Template/cluster/configmap.yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: envfile
  namespace: $NAMESPACE
data:
  CONTAINER_PLATFORM: "kubernetes"
  LOGGER_ISDEBUG: "false"
  LOGGER_MINCALLTIMESPAN: "1000"
  ContainerContent: "https://$K8S_MASTER_LB_IP:8443"
  PUBLISH_EXTERNAL_ADDRESS: "http://localhost/"
  ContainerType: "0"
  STORAGEPLATFORM: "$storageplatform"
  HTTP_PROTOCOL_TYPE: "http"
  S3_Url: "http://middle-proxy:5000"
  S3_AccessKey: "admin"
  S3_SecretKey: "root123456"
  S3_Bucket: "edoc2"
  S3_SignatureVersion: "4"
  Ceph_HealthUrl: "S3HealthUrl"
  OSS_ISCNAME: "false"
  ESURL: "http://middle-proxy:9200"
  CACHEMODULE: "redis"
  ISUDC: "0"
  PRODUCTION: "$NAMESPACE"
  INBIZ: "true"
  INBIZURL: "http://inbiz"
  INBIZGRPCURL: "http://inbiz:5003"
  INBIZV6URL: "http://inbiz-backend:5006"
  INBIZV6GRPCURL: "http://inbiz-backend:15006"
  ECMURL: "http://edoc2"
  ECMGRPCURL: "http://edoc2:5002"
  ISTITLE: "0"
  WF: "$WF"
  WEBOFFICE: "$WEBOFFICE"
  LB_RR: "true"
  APM_ESURL: "http://middle-proxy:9200"
  BACKEND_URL: "http://$K8S_MASTER_LB_IP:32800"
  MiddlewareIsCluster: "0"
  IsUsedGRPC: "1"
  ELASTICSEARCH_HOSTS: "http://middle-proxy:9200"
  ES_JAVA_OPTS: $ES_JAVA_OPTS
  COLLECT_LOG_SERVICES: '["edoc2","content","unionsync","orgsync","transport","regionsync","decryption","edrms","inbiz","auth","perm","org"]'
  API_LOG_MODULE: '["WebAPI","CoreAPI","DB","EDoc2.PermCtrl","EDoc2.Cache","EDRMS-DB","EDRMS-WEBAPI"]'
  ELASTICSEARCH_HOST: "middle-proxy"
  ELASTICSEARCH_PORT: "9200"
  RedisHostID1: "redis-sentinel0"
  RedisHostID2: "redis-sentinel1"
  RedisHostID3: "redis-sentinel2"
  RedisPort1: "26379"
  RedisPort2: "26379"
  RedisPort3: "26379"
  MinThreads: "2000"
  SKYWALKING: "true"
  RedisMasterName: mymaster
  RedisPassword: ZgDSvOoY5Q
  MQEndPoint: "middle-proxy:5672"
  DatabaseServerName: "middle-proxy"
  SyncDatabaseServerName: "middle-proxy"
  ASPNETCORE_HOSTINGSTARTUPASSEMBLIES: "SkyAPM.Agent.AspNetCore"
  privileged: "true"
  S3HealthUrl: $S3HealthUrl
  STG_MountType: "$STG_MountType"
EOF
# CLIENTSYNC: false

}

cluster_rancher() {
    get_install_path
    source $install_path"/scripts/"cluster_rancher.sh
    rancher_check_pid_file="${install_path}/pids/rancher_check.pid"
    if [ ! -f $rancher_check_pid_file ]; then
        usleep
    else
        jobs_process=`cat $rancher_check_pid_file`
        echo "#### old pid $jobs_process ####"
        kill -9 $jobs_process
        rm -rf $rancher_check_pid_file
    fi
    source "$install_path"/delete_rancher_error.sh &
    jobs_process=`jobs -l | grep -v grep | awk -F " " '{print $2}'`
    echo "#### new pid $jobs_process ####"
    echo $jobs_process > $rancher_check_pid_file
}

cluster_skywalking() {
    get_install_path
    source $install_path"/scripts/"cluster_skywalking.sh
}

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
# 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
        deploy_all
        sleep 15
        auto_cluster
        sleep 3
        echo "### install skywalking cluster ##################################"
        if [ "${SKYWALKING_STATUS}" == "true" ];then
            echo "############ xxxxx exec skywalking xxxxx #################"
            kubectl apply -f $install_path"/Template/cluster/edoc2_namespace.yaml"
            cluster_skywalking
        fi
        sleep 1
        create_apm
        sleep 3
        echo "### install rancher cluster ##################################"
        if [ "${RANCHER_STATUS}" == "true" ];then
            echo "############ xxxxx exec rancher xxxxx #################"
            cluster_rancher
        fi
        if [ "${RANCHER_STATUS}" == "true" ];then
            delete_error_rancher
        fi
        sleep 5
        auto_backup_logs_start
        ;;
    2|stop|STOP)
        get_install_path
        echo "begin stop ecm ..........."
        sleep 2
        delete_apm
        sleep 3
        delete_all 
        sleep 5
        auto_backup_logs_stop
        sleep 3
        if [ "${RANCHER_STATUS}" == "true" ];then
            delete_error_rancher
        fi
        ;;
    3|restart|RESTART)
        get_install_path
        echo "begin restart ecm ........"
        sleep 2
        delete_apm
        sleep 3
        delete_all
        sleep 5
        auto_backup_logs_stop
        sleep 3
        auto_cluster
        sleep 3
        echo "### install skywalking cluster ##################################"
        if [ "${SKYWALKING_STATUS}" == "true" ];then
            echo "############ xxxxx exec skywalking xxxxx #################"
            kubectl apply -f $install_path"/Template/cluster/edoc2_namespace.yaml"
            cluster_skywalking
        fi
        sleep 1
        echo "### install rancher cluster ##################################"
        if [ "${RANCHER_STATUS}" == "true" ];then
            echo "############ xxxxx exec rancher xxxxx #################"
            cluster_rancher
        fi
        if [ "${RANCHER_STATUS}" == "true" ];then
            delete_error_rancher
        fi
        sleep 3
        if [ "${RANCHER_STATUS}" == "true" ];then
            delete_error_rancher
        fi
        sleep 1
        pull_images_info
        sleep 1
        echo "begin deploy ecm ........."
        create_main_configmap
        sleep 5
        deploy_all
        sleep 3
        create_apm
        sleep 15
        auto_backup_logs_start
        ;;
    *)
        echo "输入操作不存在 .........."
        #exit;
esac
