#!/bin/bash

namespace=edoc2

aWorkNode01=k8s-node01
aWorkNode02=k8s-node02
aWorkNode03=k8s-node03
SSH_PORT=22


deploy_app() {
    #kubectl get pod -n $namespace | grep -v mysql | grep -v redis
    kubectl get pod -n edoc2 | grep -e nginx -e edoc2 -e transport -e content -e decryption
    if [ $? == 1 ];then
        kubectl label nodes $aWorkNode01 node.drive.nodelabels=InDrive
        kubectl label nodes $aWorkNode02 node.drive.nodelabels=InDrive
        kubectl label nodes $aWorkNode03 node.drive.nodelabels=InDrive

        # create all dep about ecm app
        if [ "$WF" == "true" ];then
           \cp  backup/wf.yaml ./
        elif [ "$WF" == "false" ];then
           mv -f wf.yaml backup/
        fi
        if [ "$WEBOFFICE" == "true" ];then
           \cp  backup/weboffice.yaml ./
        elif [ "$WEBOFFICE" == "false" ];then
           mv -f weboffice.yaml backup/
        fi
        kubectl apply -f initdatabase.yaml
        sleep 50
        kubectl apply -f .

        sleep 30

        echo "##### show all app pods status ################################"
        kubectl get pod -n $namespace
    else
        echo "##### all app deployment service has been exist! ##############"
    fi
}

delete_app() {
    echo "##### start delete all ap statefulset service #################"
    # delete statefulset servcie
    kubectl delete -f .
    
    kubectl get pod -n $namespace
    echo "##### check ecm app delete status #############################"
    while :
    do
        echo "##### check ecm app service alive! ##############################"
        kubectl get pod -n $namespace | grep -e nginx -e edoc2 -e transport -e content -e decryption
        if [ $? == 1 ];then
            break
        fi
        sleep 2
    done;
    echo "##### delete app statefulset service has successful! ########"
    sleep 1
}

cat <<eof 
**************************************
** app 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 ecmapp ........."
        deploy_app
        ;;
    2|stop|STOP)
        echo "begin stop ecmapp ..........."
        delete_app
        ;;
    3|restart|RESTART)
        echo "begin restart ecmapp ........"
        delete_app
        sleep 3
        deploy_app
        ;;
    *)
        echo "输入操作不存在 .........."
        #exit;
esac
