#!/bin/bash

namespace=$2
aWorkNode01=$3
aWorkNode02=$4
aWorkNode03=$5

# misweb-secret.yaml
# misweb.yaml


deploy_searchengine() {
    kubectl get pod -n $namespace | grep -v grep | grep searchengine
    if [ $? == 1 ];then
        echo "##### create remote pv es dir ###############################"
        sleep 1
        kubectl label nodes $aWorkNode01 node.drive.nodelabels=InDrive
        kubectl label nodes $aWorkNode02 node.drive.nodelabels=InDrive
        kubectl label nodes $aWorkNode03 node.drive.nodelabels=InDrive

        sleep 1
        kubectl apply -f searchengine.yaml

        sleep 30

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

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

    sleep 5

    echo "##### searchengine deploy and secret has been delete successful! #############"
}

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