#!/usr/bin/env bash

# NOTE: pipe and redirect does not work in this script
# ./pd-ctl.sh cluster

set -euo pipefail
# command is the all the arguments except the command name
command="$@"

# get pd image from tidbcluster .status.pd.image
image=$(kubectl get tc -n tidb${CLUSTER_ID} db -o jsonpath='{.status.pd.image}')

# apply a statefulset
echo "Creating pd-ctl debug pod..."
cat <<EOF | kubectl apply -f - > /dev/null
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: pd-ctl
spec:
  replicas: 1
  serviceName: debug-ctl
  selector:
    matchLabels:
      app: pd-ctl
  template:
    metadata:
      labels:
        app: pd-ctl
    spec:
      containers:
        - name: pd-ctl
          image: ${image}
          command: [ "tail", "-f", "/dev/null" ]
          volumeMounts:
            - name: client-ssl
              mountPath: /client-ssl
      volumes:
        - name: client-ssl
          secret:
            secretName: db-cluster-client-secret
EOF

echo "Waiting debug pod ready..."
kubectl wait --for=condition=Ready pod/pd-ctl-0 -n tidb${CLUSTER_ID} --timeout=60s > /dev/null

echo "Runnning command:"
echo "kubectl exec -it -n tidb${CLUSTER_ID} pd-ctl-0 -- /pd-ctl -u https://db-pd.tidb${CLUSTER_ID}.svc:2379 --cacert /client-ssl/ca.crt --cert /client-ssl/tls.crt --key /client-ssl/tls.key ${command}"
kubectl exec -it -n tidb${CLUSTER_ID} pd-ctl-0 -- /pd-ctl -u https://db-pd.tidb${CLUSTER_ID}.svc:2379 --cacert /client-ssl/ca.crt --cert /client-ssl/tls.crt --key /client-ssl/tls.key ${command}
