#!/usr/bin/env bash

# NOTE: pipe and redirect does not work in this script
# ./tikv-ctl.sh region-properties -r 2345

set -euo pipefail

tikvHost=${TIKV_HOST:-db-tikv-0}
# command is the rest of the arguments
command="$@"

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

echo "Creating a debug pod..."
cat <<EOF | kubectl apply -f - > /dev/null
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: tikv-ctl
spec:
  replicas: 1
  serviceName: debug-ctl
  selector:
    matchLabels:
      app: tikv-ctl
  template:
    metadata:
      labels:
        app: tikv-ctl
    spec:
      containers:
        - name: tikv-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 "Running command:"
echo "kubectl exec -it -n tidb${CLUSTER_ID} tikv-ctl-0 -- /tikv-ctl --pd https://db-pd.tidb${CLUSTER_ID}.svc:2379 --host ${tikvHost}.db-tikv-peer.tidb${CLUSTER_ID}.svc:20160 --key-path /client-ssl/tls.key --cert-path /client-ssl/tls.crt --ca-path /client-ssl/ca.crt ${command}"
kubectl exec -it -n tidb${CLUSTER_ID} tikv-ctl-0 -- /tikv-ctl --pd https://db-pd.tidb${CLUSTER_ID}.svc:2379 --host ${tikvHost}.db-tikv-peer.tidb${CLUSTER_ID}.svc:20160 --key-path /client-ssl/tls.key --cert-path /client-ssl/tls.crt --ca-path /client-ssl/ca.crt ${command}
