#!/bin/bash

namespace=edoc2

WorkNode01=k8s-node01
WorkNode02=k8s-node02
WorkNode03=k8s-node03
SSH_PORT=22

inwise_path=/home/edoc2/macrowing/edoc2v5/data/inwise

deploy_inwise() {
    kubectl get pod -n $namespace | grep -v grep | grep inwise
    if [ $? == 1 ];then
        echo "##### create remote pv es dir ###############################"
        # es-node03 标签节点
        sshpass ssh -p $SSH_PORT root@$WorkNode02 "mkdir -p $inwise_path"

        sleep 1
        kubectl label nodes $WorkNode02 node.inwise2.nodelabels=INWISE

        sleep 1
        # create statefulset servcie
        kubectl apply -f .

        sleep 30

        echo "##### show pods status ########################################################"
        kubectl get pod -n $namespace | grep -v grep | grep inwise
        echo "##### show inwise heath status ################################################"
        sleep 1
    else
        echo "##### inwise allinone deployment service has been exist! #####################"
    fi
}

delete_inwise() {
    echo "##### start delete inwise deployment service ###################################"
    # delete statefulset servcie
    kubectl delete -f .
    kubectl get pod -n $namespace | grep -v grep | grep inwise
    echo "##### check delete status #########################################################"
    while :
    do
        kubectl get pod -n $namespace | grep -v grep | grep inwise
        if [ $? == 1 ];then
            break
        fi
        sleep 2
    done;
    sleep 1
    echo "##### delete inwise deployment service has successful! ###############################"
}

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

caliconode=`cat /etc/hosts | grep node | awk -F " " '{print $2}'`
if [ "${caliconode:0:1}" == "" ];then
    echo "##### caliconode host is empty #############################"
else
    echo "##### caliconode check status exist ########################"
    for cnode in $caliconode;do
        echo ${cnode};
        calicoip=`cat /etc/hosts | grep ${cnode} | awk -F " " '{print $1}'`
        calicoctl patch node ${cnode} --patch="{\"spec\":{\"bgp\": {\"ipv4Address\": \"$calicoip/24\"}}}" --allow-version-mismatch
    done
fi

sleep 3
Action=$1
case $Action in 
    1|start|START)
        echo "begin deploy inwise ........."
        deploy_inwise
        ;;
    2|stop|STOP)
        echo "begin stop inwise ..........."
        delete_inwise
        ;;
    3|restart|RESTART)
        echo "begin restart inwise ........"
        delete_inwise
        sleep 3
        deploy_inwise
        ;;
    *)
        echo "输入操作不存在 .........."
        #exit;
esac
