#!/bin/bash

namespace=$2

WorkNode01=$3
WorkNode02=$4
WorkNode03=$5
SSH_PORT=$6


deploy_proxy() {
    kubectl get pod -n $namespace | grep -v grep | grep proxy
    if [ $? == 1 ];then
        kubectl label nodes $WorkNode01 node.labels.nodelabels=Middleware
        kubectl label nodes $WorkNode02 node.labels.nodelabels=Middleware
        kubectl label nodes $WorkNode03 node.labels.nodelabels=Middleware

        # create sc pv
        kubectl apply -f haproxy-secret.yaml
        kubectl apply -f middle-haproy-cnf.yaml
        sleep 1
        # create statefulset servcie
        kubectl apply -f middle-proxy.yaml

        sleep 9

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

delete_proxy() {
    echo "##### start delete proxy deployment service ##################"
    # delete statefulset servcie
    kubectl delete -f middle-proxy.yaml
    
    kubectl get pod -n $namespace | grep -v grep | grep proxy
    echo "##### check delete status ##################################"
    while :
    do
        echo "##### check proxy service alive! ###########################"
        kubectl get pod -n $namespace | grep -v grep | grep proxy
        if [ $? == 1 ];then
            break
        fi
        sleep 2
    done;
    echo "##### delete proxy dep service has successful! ########" 
    sleep 1
    # delete sc pv
    kubectl delete -f middle-haproy-cnf.yaml
    kubectl delete -f haproxy-secret.yaml
    sleep 1
    echo "##### proxy configmap has been delete successful! #############"
}

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