#!/bin/bash

# 设置命名空间
NAMESPACE="xmyd"

desired_deployment_name="cmii"

change_to_integration() {
  echo "[change_to_integration] - namespace set to uavcloud-test!"
  NAMESPACE="uavcloud-test"
  echo ""
}

change_to_validation() {
  echo "[change_to_validation] - namespace set to uavcloud-feature!"
  NAMESPACE="uavcloud-feature"
  echo ""
}

change_to_uat() {
  echo "[change_to_uat] - namespace set to change_to_uat!"
  NAMESPACE="uavcloud-uat"
  echo ""
}

restart_deployment() {

  local need_to_scale_up_deployments
  # shellcheck disable=SC2207
  need_to_scale_up_deployments=($(kubectl get deployments -n $NAMESPACE -o=jsonpath='{.items[*].metadata.name}' | tr " " "\n"))

  local deployment_name
  local desired_replica_count
  for deployment_name in "${need_to_scale_up_deployments[@]}"; do
    if echo "$deployment_name" | grep -qE "${desired_deployment_name}"; then
      echo "[RESTART] - namespace of [$NAMESPACE] deployment of [$deployment_name] need to RESTART !"
      echo ""
      desired_replica_count=$(kubectl -n "$NAMESPACE" get deployment "$deployment_name" -o=jsonpath='{.spec.replicas}')
      kubectl scale deployment "$deployment_name" --replicas=0 -n "$NAMESPACE"
      echo "[SCALE] - namespace of [$NAMESPACE] deployment of [$deployment_name] desired_replica_count is $desired_replica_count"
      kubectl scale deployment "$deployment_name" --replicas="${desired_replica_count}" -n "$NAMESPACE"
      echo ""
    fi
  done

}

change_replica_of_deployment() {

  if [ "$1" == "" ]; then
    echo "[change_replica_of_deployment] - desired_replica_count is null , can not execute !"
    return 233
  fi
  local desired_replica_count
  desired_replica_count=$1

  if [ "${desired_deployment_name}" == "" ]; then
    echo "[change_replica_of_deployment] - WARNING all deployment of [$NAMESPACE] will be SCALE to => [$desired_replica_count] !!"
  fi

  local all_deployment_name_list
  # shellcheck disable=SC2207
  all_deployment_name_list=($(kubectl get deployments -n $NAMESPACE -o=jsonpath='{.items [*].metadata.name}' | tr " " "\n"))

  local deployment_name
  for deployment_name in "${all_deployment_name_list[@]}"; do
    if echo "$deployment_name" | grep -qE "${desired_deployment_name}"; then
      echo ""
      echo "[SCALE] - namespace of [$NAMESPACE] deployment of [$deployment_name] SCALE TO => [$desired_replica_count]"
      kubectl scale deployment "$deployment_name" --replicas="${desired_replica_count}" -n "$NAMESPACE"
      echo ""
    fi
  done

}

main() {

  # 修改环境
 change_to_validation

  # 模糊匹配
  # 空则匹配命名空间中的全部deployment
#  desired_deployment_name="bitbu"

  # 重启 deployment1
  #  restart_deployment

  # 改变deployment的副本数量
  change_replica_of_deployment 1

}

main
