#!/usr/bin/env bash

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

set -euo pipefail
source lib.sh

usage() {
    cat <<EOF
Deploy a debug pod and run tikv-ctl command in it.

Usage: tikv-ctl.sh [-h] [subcommands]

  -h     show this message and exit

Examples:

  ./tikv-ctl.sh store

Environments:

  TIKV_HOST     tikv host to connect, default to 'db-tikv-0'
EOF
}

while getopts "h?" opt; do
    case "$opt" in
    h|\?)
        usage
        exit 0
        ;;
    esac
done

COMMAND="$@"
CLUSTER_ID=$(lib::require_cluster_id)
CLUSTER_NS="tidb${CLUSTER_ID}"

if [[ -z "${CLUSTER_ID}" ]]; then
    echo "Cluster id is empty, please check your kubectl context."
    exit 1
fi

DEBUG_STS_NAME="tikv-ctl"
DEBUG_POD_NAME="tikv-ctl-0"
DEBUG_POD_NS=${CLUSTER_NS}

DEBUG_STS_EXIST=$(kubectl get sts -n ${DEBUG_POD_NS} ${DEBUG_STS_NAME} 2>/dev/null | wc -l)
if [[ ${DEBUG_STS_EXIST} -eq 0 ]]; then
    # get tikv image from tidbcluster .status.tikv.image
    DEBUG_IMAGE=$(kubectl get tc -n ${CLUSTER_NS} db -o jsonpath='{.status.tikv.image}')


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

    lib::wait_pod_ready ${DEBUG_POD_NS} ${DEBUG_POD_NAME}
fi

TIKV_HOST=${TIKV_HOST:-db-tikv-0}
echo "Running command:"
echo "kubectl exec -it -n ${DEBUG_POD_NS} ${DEBUG_POD_NAME} -- /tikv-ctl --pd https://db-pd.${CLUSTER_NS}.svc:2379 --host ${TIKV_HOST}.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 ${DEBUG_POD_NS} ${DEBUG_POD_NAME} -- /tikv-ctl --pd https://db-pd.${CLUSTER_NS}.svc:2379 --host ${TIKV_HOST}.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}
