#!/bin/bash


all_unhealthy_pod_list=""

all_cmii_name_space=(uavcloud-test uavcloud-feature uavcloud-uat uavcloud-dev uavcloud-devflight uavcloud-devoperation)
clean_up_log="clean_unhealthy_pod_log_$(date +'%Y-%m-%d-%H-%M-%S')"
mkdir -p /root/wdd
touch "/root/wdd/${clean_up_log}"
echo "clean log is => /root/wdd/$clean_up_log"

echo ""
for name_space in "${all_cmii_name_space[@]}"; do
  echo "[NAMESPACE] - start to deal with namespace [$name_space]"
  if ! kubectl get ns "$name_space"; then
      echo "[NAMESPACE] - namespace of [$name_space] not exists !"
      echo ""
      continue
  fi

  # shellcheck disable=SC2207
  all_unhealthy_pod_list=($(kubectl get pods --field-selector=status.phase!=Running,status.phase!=Succeeded -n "$name_space" -o=jsonpath='{.items[*].metadata.name}' | tr " " "\n"))
  for unhealthy_pod in "${all_unhealthy_pod_list[@]}"; do
    echo ""
    if ! echo "$unhealthy_pod" | grep -q "mysql|redis|rabbit|mongo|nacos|srs"; then
      clean_log="[clean_up] start to clean namespace [$name_space] unhealthy pod of => $unhealthy_pod"
      echo "${clean_log}" >>"/root/wdd/$clean_up_log"
      echo "${clean_log}"
      kubectl -n "$name_space" delete pod "$unhealthy_pod" --force
    else
      clean_log="[clean_up] namespace [$name_space] unhealthy pod of => $unhealthy_pod not clean !"
      echo "${clean_log}" >>"/root/wdd/$clean_up_log"
      echo "${clean_log}"
    fi

    echo "[NAMESPACE] - accomplished!"
    echo ""
  done
done
