#!/bin/bash

# This script is used to delete useless Pod, PVC and PV when a tidb-cluster was deleted in test environment.

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"

set -o errexit
set -o nounset
set -o pipefail

tidbclusters=$(kubectl get tc --no-headers -o custom-columns=":metadata.name" --all-namespaces | xargs)
pvc_namespaces=$(kubectl get pvc --all-namespaces -l 'app.kubernetes.io/managed-by in (tidb-operator, backup-opeartor, restore-operator)' --no-headers -o custom-columns=":metadata.namespace" | sort | uniq -c | awk '{print $2}' | xargs)

deletePod() {
  echo "delete all pods in namespace[$1]"
  kubectl delete pods --all --grace-period=0 --force -n $1
}

deletePVC() {
  echo "delete PVC in namespace[$1]"
  kubectl delete pvc -n $1 -l "app.kubernetes.io/instance=$1,app.kubernetes.io/managed-by in (tidb-operator, backup-opeartor, restore-operator)"
}

deletePV() {
  echo "set PV's persistentVolumeReclaimPolicy to Delete in namespace[$1]"
  kubectl get pv -l "app.kubernetes.io/namespace=$1,app.kubernetes.io/instance=$1,app.kubernetes.io/managed-by in (tidb-operator, backup-opeartor, restore-operator)" -o name | xargs -I {} kubectl patch {} -p '{"spec":{"persistentVolumeReclaimPolicy":"Delete"}}'
}

for pvc_ns in ${pvc_namespaces}
do
  stat=0
  for tc in ${tidbclusters}
  do
    if [ $pvc_ns == $tc ];then
      stat=1
      break
    fi
  done

  if [ $stat -ne 1 ];then
    deletePod $pvc_ns
    deletePVC $pvc_ns
    deletePV $pvc_ns
  fi
done
