#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=scripts/cluster/common.sh
source "$script_dir/common.sh"

target_primary=${1:-}
[[ $target_primary =~ ^easyai-postgres-[12]$ ]] || {
  echo 'usage: promote-cnpg-primary.sh easyai-postgres-{1|2}' >&2
  exit 64
}

load_cluster_env
cluster_ssh "$CLUSTER_NINGBO_HOST" bash -s -- "$target_primary" <<'REMOTE'
set -euo pipefail
target_primary=$1
kubectl='k3s kubectl'
command -v kubectl-cnpg >/dev/null
[[ $($kubectl get pod "$target_primary" -n easyai \
  -o jsonpath='{.metadata.labels.cnpg\.io/cluster}') == easyai-postgres ]]
current_primary=$($kubectl get cluster easyai-postgres -n easyai \
  -o jsonpath='{.status.currentPrimary}')
if [[ $current_primary != "$target_primary" ]]; then
  $kubectl cnpg promote easyai-postgres "$target_primary" -n easyai
fi
for _ in $(seq 1 120); do
  current_primary=$($kubectl get cluster easyai-postgres -n easyai \
    -o jsonpath='{.status.currentPrimary}')
  ready_instances=$($kubectl get cluster easyai-postgres -n easyai \
    -o jsonpath='{.status.readyInstances}')
  if [[ $current_primary == "$target_primary" && $ready_instances == 2 ]]; then
    synchronous_replicas=$($kubectl exec -n easyai "$current_primary" -c postgres -- \
      psql -X -U postgres -d postgres -At -c \
      "SELECT count(*) FROM pg_stat_replication WHERE sync_state IN ('sync','quorum');")
    if [[ $synchronous_replicas == 1 ]]; then
      echo "cnpg_primary_promotion=PASS primary=$current_primary synchronous_replicas=1"
      exit 0
    fi
  fi
  sleep 3
done
echo "CNPG did not converge on target primary: $target_primary" >&2
exit 1
REMOTE
