#!/bin/bash

function upgrade_crd()
{
    apiVersion=`kubectl get crd  logconfigs.cls.cloud.tencent.com -o yaml | grep "apiVersion" | head -n 1 | awk '{print $2}'`
    if [ "$apiVersion" == "apiextensions.k8s.io/v1" ]; then
        kubectl apply -f https://mirrors.tencent.com/install/cls/k8s/upgrade/crd.yaml
    elif [ "$apiVersion" == "apiextensions.k8s.io/v1beta1" ]; then
        kubectl apply -f https://mirrors.tencent.com/install/cls/k8s/upgrade/crd-beta-no-nullable.yaml
    else
        echo "[FAIL] kubernetes crd apiVersion is ${apiVersion}"
        exit 1
    fi

    if [ $? != 0 ]; then
        echo "[FAIL] upgrade tencent-cloud-cls crd failed"
        exit 1
    fi
}

function upgrade_clusterrole(){
    kubectl apply -f https://mirrors.tencent.com/install/cls/k8s/upgrade/clusterrole.yaml
    if [ $? != 0 ]; then
        echo "[FAIL] upgrade clusterrole failed"
        exit 1
    fi
}

function upgrade()
{
    kubectl patch ds tke-log-agent -n kube-system -p '{"spec":{"template":{"spec":{"containers":[{"name":"log-agent","image":"ccr.ccs.tencentyun.com/tkeimages/log-agent:v1.1.15.1", "env":[{"name":"IS_PERSONAL_KUBE","value":"true"}]},{"name":"loglistener","image":"ccr.ccs.tencentyun.com/tkeimages/loglistener:v2.9.0"}]}}}}'
    if [ $? != 0 ]; then
        echo "[FAIL] upgrade tencent-cloud-cls tke-log-agent failed"
        exit 1
    fi

    kubectl patch deploy cls-provisioner -n kube-system -p '{"spec":{"template":{"spec":{"containers":[{"name":"cls-provisioner","image":"ccr.ccs.tencentyun.com/tkeimages/cls-provisioner:v1.1.15.1","env":[{"name":"IS_PERSONAL_KUBE","value":"true"}]}]}}}}'
    if [ $? != 0 ]; then
        echo "[FAIL] upgrade tencent-cloud-cls cls-provisioner failed"
        exit 1
    fi
}

function main()
{
    upgrade_crd
    upgrade_clusterrole
    upgrade
}

main $@
