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

if [ "$#" -ne 3 ]; then
  echo "usage: $0 <kubeconfig> <context> <session-context-json>" >&2
  exit 64
fi

kubeconfig=$1
context=$2
context_json=$3
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo_root=$(cd "$script_dir/../../../.." && pwd)

organization_id=1440003
network_cidr=10.0.0.0/16
service_cidr=172.20.0.0/16
wait_seconds=${CP9_ESSENTIAL_V2_SHARED_POOL_WAIT_SECONDS:-3600}
poll_interval=${CP9_ESSENTIAL_V2_SHARED_POOL_POLL_INTERVAL:-20}
discovery_wait_seconds=${CP9_ESSENTIAL_V2_DISCOVERY_WAIT_SECONDS:-120}
mode=${CP9_ESSENTIAL_V2_MODE:-activate}
status_file=${CP9_ESSENTIAL_V2_STATUS_FILE:-}
create_attempt_file=${status_file:+$status_file.create-attempt}

case "$mode" in
  activate|status) ;;
  *)
    echo "unsupported CP9_ESSENTIAL_V2_MODE: $mode" >&2
    exit 64
    ;;
esac
if [ "$mode" = "activate" ] && [ "$create_attempt_file" = "" ]; then
  echo "CP9_ESSENTIAL_V2_STATUS_FILE is required for crash-safe activation" >&2
  exit 64
fi

runtime_json=$(
  python3 - "$context_json" "$network_cidr" "$service_cidr" <<'PY'
import json
import re
import sys

with open(sys.argv[1], "r", encoding="utf-8") as f:
    ctx = json.load(f)

target = ctx.get("target") or {}
essential_v2 = ctx.get("essential_v2") or {}
session_tags = ctx.get("session_tags") or {}
account = str(target.get("account") or "").strip()
cloud = str(target.get("cloud") or "").strip()
region = str(target.get("region") or "").strip()
session_name = str(ctx.get("session_name") or "").strip()
owner = str(session_tags.get("cp9-owner") or "").strip()
session_tag = str(session_tags.get("cp9-session") or "").strip()
ttl = str(ctx.get("ttl_expires_at") or "").strip()
pca_arn = str((((ctx.get("terraform") or {}).get("session_product_pca") or {}).get("arn")) or "").strip()
enabled_tikv_remote_workers = essential_v2.get("enabled_tikv_remote_workers") or [
    "TIKV_WORKER",
    "COPROCESSOR_WORKER",
]

if cloud != "aws" or region != "us-west-2":
    raise SystemExit("Essential V2 Dev Full activation currently requires target cloud=aws and region=us-west-2")
if not re.fullmatch(r"\d{12}", account):
    raise SystemExit("CP9_SESSION_CONTEXT.target.account must be a 12-digit AWS account id")
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{1,30}[a-z0-9]", session_name):
    raise SystemExit("CP9_SESSION_CONTEXT.session_name must be a 3-32 character DNS-compatible name")
if not owner or owner == "required":
    raise SystemExit("CP9_SESSION_CONTEXT.session_tags.cp9-owner is required")
if session_tag != session_name:
    raise SystemExit("CP9_SESSION_CONTEXT.session_tags.cp9-session must equal session_name")
if not ttl:
    raise SystemExit("CP9_SESSION_CONTEXT.ttl_expires_at is required")
if not re.fullmatch(
    rf"arn:aws(?:-[a-z0-9-]+)?:acm-pca:{re.escape(region)}:{account}:"
    r"certificate-authority/[0-9a-fA-F-]+",
    pca_arn,
):
    raise SystemExit("CP9_SESSION_CONTEXT.terraform.session_product_pca.arn must be a target-account ACM PCA ARN")

allowed_workers = {"TIKV_WORKER", "COPROCESSOR_WORKER"}
if not enabled_tikv_remote_workers or any(worker not in allowed_workers for worker in enabled_tikv_remote_workers):
    raise SystemExit("Essential V2 enabled_tikv_remote_workers contains an unsupported value")

print(json.dumps({
    "pool_name": session_name,
    "session_name": session_name,
    "owner": owner,
    "ttl": ttl.replace(":", "-"),
    "network_cidr": sys.argv[2],
    "service_cidr": sys.argv[3],
    "pca_arn": pca_arn,
    "enabled_tikv_remote_workers": enabled_tikv_remote_workers,
}, separators=(",", ":")))
PY
)

pool_name=$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["pool_name"])' "$runtime_json")
owner=$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["owner"])' "$runtime_json")
ttl=$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["ttl"])' "$runtime_json")

lock_owned=false
if [ "$mode" = "activate" ]; then
  # ponytail: activation has one controller host; use its atomic mkdir rather
  # than adding a distributed lock until multi-host activation exists.
  lock_dir="${TMPDIR:-/tmp}/cp9-essential-v2-${pool_name}.lock.d"
  for _ in 1 2; do
    if mkdir "$lock_dir" 2>/dev/null; then
      printf '%s\n' "$$" >"$lock_dir/pid"
      lock_owned=true
      break
    fi
    holder=$(cat "$lock_dir/pid" 2>/dev/null || true)
    if [ "$holder" != "" ] && kill -0 "$holder" 2>/dev/null; then
      echo "another Essential V2 activation is already running for session $pool_name" >&2
      exit 1
    fi
    rm -f "$lock_dir/pid"
    rmdir "$lock_dir" 2>/dev/null || true
  done
  if [ "$lock_owned" != true ]; then
    echo "could not acquire the Essential V2 activation lock for session $pool_name" >&2
    exit 1
  fi
fi

tmpdir=$(mktemp -d)
cleanup() {
  if [ "${pf_pid:-}" != "" ] && kill -0 "$pf_pid" 2>/dev/null; then
    kill "$pf_pid" 2>/dev/null || true
    wait "$pf_pid" 2>/dev/null || true
  fi
  rm -rf "$tmpdir"
  if [ "$lock_owned" = true ] && [ "$(cat "$lock_dir/pid" 2>/dev/null || true)" = "$$" ]; then
    rm -f "$lock_dir/pid"
    rmdir "$lock_dir" 2>/dev/null || true
  fi
}
trap cleanup EXIT

response_file="$tmpdir/response.json"
grpc_result="$tmpdir/grpc-result.json"
grpc_stderr="$tmpdir/grpc-stderr.log"
grpc_client="$tmpdir/cp9-grpc-json"
profile_file="$tmpdir/resource-pool-profile.json"
list_payload="$tmpdir/list-resource-pools.json"
get_payload="$tmpdir/get-resource-pool.json"
create_payload="$tmpdir/create-resource-pool.json"
create_attempt_payload="$tmpdir/create-attempt.json"
strategy_payload="$tmpdir/update-resource-pool-strategy.json"
pf_log="$tmpdir/tidb-mgmt-service-port-forward.log"
resource_pool_service=/tidb_mgmt_service.v1.ResourcePoolService

if ! (cd "$repo_root" && go build -o "$grpc_client" ./cmd/cp9-grpc-json) 2>"$grpc_stderr"; then
  echo "Could not build the repository-owned gRPC client:" >&2
  cat "$grpc_stderr" >&2 || true
  exit 1
fi

pick_port() {
  python3 <<'PY'
import socket

with socket.socket() as sock:
    sock.bind(("127.0.0.1", 0))
    print(sock.getsockname()[1])
PY
}

service_ready() {
  KUBECONFIG="$kubeconfig" kubectl --context "$context" --namespace cp9-global \
    get svc/tidb-mgmt-service >/dev/null 2>&1 &&
    [ "$(KUBECONFIG="$kubeconfig" kubectl --context "$context" --namespace cp9-global \
      get endpoints/tidb-mgmt-service -o jsonpath='{.subsets[*].addresses[*].ip}' 2>/dev/null)" != "" ]
}

for _ in $(seq 1 120); do
  if service_ready; then
    break
  fi
  sleep 2
done

if ! service_ready; then
  echo "Timed out waiting for tidb-mgmt-service endpoint" >&2
  exit 1
fi

if ! KUBECONFIG="$kubeconfig" kubectl --context "$context" --namespace cp9-global \
  rollout status statefulset/tidb-mgmt-service --timeout=300s; then
  echo "Timed out waiting for tidb-mgmt-service statefulset" >&2
  exit 1
fi

port=$(pick_port)
KUBECONFIG="$kubeconfig" kubectl --context "$context" --namespace cp9-global \
  port-forward --address 127.0.0.1 svc/tidb-mgmt-service "$port:10001" >"$pf_log" 2>&1 &
pf_pid=$!

grpc_request() {
  local method=$1
  local body=$2
  local fence=${3:-}
  local fence_payload=${4:-}
  local args=(
    --address "127.0.0.1:$port"
    --method "$resource_pool_service/$method"
    --request "$body"
    --timeout 300s
  )
  if [ "$fence" != "" ]; then
    args+=(--before-invoke-fence "$fence" --before-invoke-fence-payload "$fence_payload")
  fi
  : >"$grpc_result"
  : >"$grpc_stderr"
  if ! "$grpc_client" "${args[@]}" >"$grpc_result" 2>"$grpc_stderr"; then
    return 70
  fi
  grpc_code=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["code"])' "$grpc_result")
  grpc_message=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("message", ""))' "$grpc_result")
  if [ "$grpc_code" = "OK" ]; then
    python3 - "$grpc_result" "$response_file" <<'PY'
import json
import pathlib
import sys

result = json.loads(pathlib.Path(sys.argv[1]).read_text())
pathlib.Path(sys.argv[2]).write_text(json.dumps(result.get("response") or {}, separators=(",", ":")) + "\n")
PY
  else
    printf '{}\n' >"$response_file"
  fi
}

is_retryable_grpc_code() {
  case "$1" in
    Aborted|Canceled|DataLoss|DeadlineExceeded|Internal|ResourceExhausted|Unavailable|Unknown) return 0 ;;
    *) return 1 ;;
  esac
}

python3 - "$pool_name" >"$list_payload" <<'PY'
import json
import sys

json.dump({
    "resourcePoolName": sys.argv[1],
    "providerIds": ["AWS"],
    "regionIds": ["AWS_US_WEST_2"],
    "ownerType": "SHARED",
    "ownerIds": ["0"],
    "servicePlan": "Essential_V2",
    "pageSize": 100,
    "view": "DETAIL",
}, sys.stdout, separators=(",", ":"))
PY

for _ in $(seq 1 60); do
  if ! kill -0 "$pf_pid" 2>/dev/null; then
    echo "tidb-mgmt-service port-forward exited early:" >&2
    cat "$pf_log" >&2 || true
    exit 1
  fi
  if ! grpc_request ListResourcePools "$list_payload"; then
    echo "tidb-management-service gRPC client failed:" >&2
    cat "$grpc_stderr" >&2 || true
    exit 1
  fi
  if [ "$grpc_code" = "OK" ]; then
    break
  fi
  if ! is_retryable_grpc_code "$grpc_code"; then
    if [ "$grpc_code" = "Unimplemented" ]; then
      echo "tidb-mgmt-service gRPC port 10001 does not expose the required reflection API" >&2
    fi
    echo "ListResourcePools readiness probe failed with gRPC $grpc_code: $grpc_message" >&2
    exit 1
  fi
  sleep 1
done

if [ "${grpc_code:-Unavailable}" != "OK" ]; then
  echo "Timed out waiting for tidb-mgmt-service gRPC endpoint through port-forward $port" >&2
  cat "$pf_log" >&2 || true
  exit 1
fi

write_runtime_status() {
  state=$1
  pool_id=$2
  dataplane_name=$3
  phase=$4
  version=$5
  message=$6
  [ "$status_file" != "" ] || return 0
  mkdir -p "$(dirname "$status_file")"
  python3 - "$status_file" "$state" "$pool_id" "$dataplane_name" "$phase" "$version" "$message" <<'PY'
import json
import pathlib
import sys

path = pathlib.Path(sys.argv[1])
payload = {
    "state": sys.argv[2],
    "shared_pool_id": sys.argv[3],
    "dataplane_name": sys.argv[4],
    "phase": sys.argv[5],
    "version": sys.argv[6],
    "message": sys.argv[7],
}
path.write_text(json.dumps(payload, separators=(",", ":")) + "\n", encoding="utf-8")
PY
}

write_create_attempt_payload() {
  python3 - "$create_attempt_payload" "$pool_name" "$owner" <<'PY'
import json
import pathlib
import sys

path = pathlib.Path(sys.argv[1])
path.write_text(json.dumps({
    "pool_name": sys.argv[2],
    "owner": sys.argv[3],
    "state": "create_sent",
}, separators=(",", ":")) + "\n", encoding="utf-8")
PY
}

validate_create_attempt() {
  python3 - "$create_attempt_file" "$pool_name" "$owner" <<'PY'
import json
import pathlib
import sys

attempt = json.loads(pathlib.Path(sys.argv[1]).read_text())
if attempt != {"pool_name": sys.argv[2], "owner": sys.argv[3], "state": "create_sent"}:
    raise SystemExit("Essential V2 create-attempt fence does not match this session")
PY
}

clear_create_attempt() {
  [ "$create_attempt_file" != "" ] || return 0
  rm -f "$create_attempt_file"
}

discover_pool() {
  if ! grpc_request ListResourcePools "$list_payload"; then
    echo "ListResourcePools gRPC client failed:" >&2
    cat "$grpc_stderr" >&2 || true
    return 2
  fi
  if [ "$grpc_code" != "OK" ]; then
    if is_retryable_grpc_code "$grpc_code"; then
      return 75
    fi
    echo "ListResourcePools failed with gRPC $grpc_code: $grpc_message" >&2
    return 2
  fi

  python3 - "$response_file" "$profile_file" "$pool_name" "$owner" "$ttl" <<'PY'
import json
import pathlib
import sys

data = json.loads(pathlib.Path(sys.argv[1]).read_text())
name = sys.argv[3]
owner = sys.argv[4]
named = []
matches = []
for profile in data.get("resourcePools") or []:
    pool = profile.get("resourcePool") or {}
    if str(pool.get("name") or "").strip() != name:
        continue
    named.append(profile)
    tags = pool.get("cloudResourceTags") or {}
    if (
        pool.get("ownerType") == "SHARED"
        and str(pool.get("ownerId") or "0") == "0"
        and pool.get("providerId") == "AWS"
        and pool.get("regionId") == "AWS_US_WEST_2"
        and pool.get("servicePlan") == "Essential_V2"
        and tags.get("cp9-session") == name
        and tags.get("cp9-owner") == owner
        and tags.get("cp9-managed") == "true"
        and tags.get("cp9-ttl") == sys.argv[5]
        and pool.get("createdBy") == "cp9/" + name
    ):
        matches.append(profile)

if not named:
    raise SystemExit(10)
if len(named) != 1 or len(matches) != 1:
    print(
        f"found {len(named)} live pools named {name!r}, but {len(matches)} match the exact CP9 session identity; refusing ambiguous ownership",
        file=sys.stderr,
    )
    raise SystemExit(2)
pathlib.Path(sys.argv[2]).write_text(json.dumps(matches[0], separators=(",", ":")) + "\n")
PY
}

validate_profile() {
  expected_id=${1:-}
  python3 - "$profile_file" "$pool_name" "$expected_id" "$owner" "$ttl" <<'PY'
import json
import pathlib
import sys

profile = json.loads(pathlib.Path(sys.argv[1]).read_text())
pool = profile.get("resourcePool") or {}
tags = pool.get("cloudResourceTags") or {}
expected = {
    "name": sys.argv[2],
    "ownerType": "SHARED",
    "providerId": "AWS",
    "regionId": "AWS_US_WEST_2",
    "servicePlan": "Essential_V2",
}
for key, value in expected.items():
    if pool.get(key) != value:
        raise SystemExit(f"resource pool {key} mismatch: expected {value!r}, got {pool.get(key)!r}")
if str(pool.get("ownerId") or "0") != "0":
    raise SystemExit("Essential V2 resource pool ownerId must be 0")
if tags.get("cp9-session") != sys.argv[2] or tags.get("cp9-owner") != sys.argv[4]:
    raise SystemExit("Essential V2 resource pool CP9 session identity does not match this session")
if tags.get("cp9-managed") != "true" or tags.get("cp9-ttl") != sys.argv[5]:
    raise SystemExit("Essential V2 resource pool cleanup tags do not match this session")
if pool.get("createdBy") != "cp9/" + sys.argv[2]:
    raise SystemExit("Essential V2 resource pool creator identity does not match this session")
pool_id = str(pool.get("id") or "")
if not pool_id.isdigit() or int(pool_id) == 0:
    raise SystemExit("CreateResourcePool/GetResourcePool did not return a generated resource pool id")
if sys.argv[3] and pool_id != sys.argv[3]:
    raise SystemExit(f"resource pool id changed: expected {sys.argv[3]}, got {pool_id}")
PY
}

profile_value() {
  key=$1
  python3 - "$profile_file" "$key" <<'PY'
import json
import pathlib
import sys

profile = json.loads(pathlib.Path(sys.argv[1]).read_text())
if sys.argv[2] == "version":
    value = profile.get("version") or ""
else:
    value = (profile.get("resourcePool") or {}).get(sys.argv[2]) or ""
print(value)
PY
}

profile_has_default_org() {
  python3 - "$profile_file" "$organization_id" <<'PY'
import json
import pathlib
import sys

profile = json.loads(pathlib.Path(sys.argv[1]).read_text())
raise SystemExit(0 if sys.argv[2] in {str(value) for value in profile.get("defaultOrgs") or []} else 1)
PY
}

get_pool() {
  pool_id=$1
  printf '{"resourcePoolId":"%s"}\n' "$pool_id" >"$get_payload"
  if ! grpc_request GetResourcePool "$get_payload"; then
    echo "GetResourcePool $pool_id gRPC client failed:" >&2
    cat "$grpc_stderr" >&2 || true
    return 2
  fi
  if [ "$grpc_code" != "OK" ]; then
    if is_retryable_grpc_code "$grpc_code"; then
      return 75
    fi
    echo "GetResourcePool $pool_id failed with gRPC $grpc_code: $grpc_message" >&2
    return 2
  fi
  cp "$response_file" "$profile_file"
  validate_profile "$pool_id"
}

write_profile_status() {
  pool_id=$(profile_value id)
  dataplane_name=$(profile_value dataplaneId)
  lifecycle_state=$(profile_value lifecycleState)
  version=$(profile_value version)
  state_message_code=$(profile_value stateMessageCode)
  phase=${lifecycle_state:-LIFECYCLE_STATE_UNSPECIFIED}

  if [ "$phase" != "ACTIVE" ]; then
    write_runtime_status "not_ready" "$pool_id" "$dataplane_name" "$phase" "$version" \
      "Essential V2 resource pool lifecycle ${phase}${state_message_code:+: $state_message_code}" || return 2
    return 1
  fi
  if [ "$dataplane_name" = "" ] || [ "$version" = "" ]; then
    write_runtime_status "not_ready" "$pool_id" "$dataplane_name" "$phase" "$version" \
      "Essential V2 resource pool owner profile is missing dataplane or version identity" || return 2
    return 1
  fi
  if ! profile_has_default_org; then
    write_runtime_status "not_ready" "$pool_id" "$dataplane_name" "$phase" "$version" \
      "Essential V2 resource pool is not the default for organization $organization_id" || return 2
    return 1
  fi
  write_runtime_status "ready" "$pool_id" "$dataplane_name" "$phase" "$version" \
    "Essential V2 resource pool is ACTIVE through tidb-management-service" || return 2
  return 0
}

if discover_pool; then
  validate_profile ""
  if [ "$mode" = "activate" ]; then
    clear_create_attempt
  fi
else
  discover_status=$?
  if [ "$discover_status" -eq 75 ]; then
    echo "ListResourcePools is temporarily unavailable" >&2
    exit 1
  fi
  if [ "$discover_status" -ne 10 ]; then
    exit 1
  fi
  if [ "$mode" = "status" ]; then
    if [ -f "$create_attempt_file" ]; then
      validate_create_attempt
      write_runtime_status "not_ready" "" "" "CREATE_OUTCOME_UNKNOWN" "" \
        "A prior CreateResourcePool call has no discoverable owner record; destroy and recreate the session after reconciling tagged resources"
    else
      write_runtime_status "not_ready" "" "" "NOT_FOUND" "" \
        "Essential V2 resource pool is absent; run cp9 essential-v2 activate"
    fi
    exit 0
  fi
  if [ -f "$create_attempt_file" ]; then
    validate_create_attempt
    message="A prior CreateResourcePool call has no discoverable owner record; refusing to send another create. Destroy and recreate the session after reconciling tagged resources."
    write_runtime_status "not_ready" "" "" "CREATE_OUTCOME_UNKNOWN" "" "$message"
    echo "$message" >&2
    exit 1
  fi

  python3 - "$runtime_json" >"$create_payload" <<'PY'
import json
import sys

runtime = json.loads(sys.argv[1])
storage = lambda size: {
    "storageType": "GP3",
    "diskSizeGi": size,
    "diskIops": 3000,
    "diskThroughputMbps": 125,
}
payload = {
    "resourcePool": {
        "name": runtime["pool_name"],
        "providerId": "AWS",
        "regionId": "AWS_US_WEST_2",
        "ownerType": "SHARED",
        "ownerId": "0",
        "cidr": runtime["network_cidr"],
        "servicePlan": "Essential_V2",
        "instanceLimit": "50",
        "k8sServiceCidr": runtime["service_cidr"],
        "pcaArn": runtime["pca_arn"],
        "highAvailabilityType": "REGIONAL",
        "cloudResourceTags": {
            "cp9-managed": "true",
            "cp9-owner": runtime["owner"],
            "cp9-persona": "premium",
            "cp9-session": runtime["session_name"],
            "cp9-ttl": runtime["ttl"],
        },
    },
    "demand": {
        "initialRcu": 20000,
        "tikvData": storage(100),
        "tikvRaftlog": storage(40),
        "tiflashCn": storage(100),
        "tiflashWn": storage(100),
    },
    "pdDeploymentMode": "PD_DEPLOYMENT_MODE_MONOLITHIC",
    "enabledTikvRemoteWorkers": runtime["enabled_tikv_remote_workers"],
    "createdBy": "cp9/" + runtime["session_name"],
}
json.dump(payload, sys.stdout, separators=(",", ":"))
PY

  write_create_attempt_payload
  echo "Creating Essential V2 resource pool through tidb-management-service"
  create_client_status=0
  grpc_request CreateResourcePool "$create_payload" "$create_attempt_file" "$create_attempt_payload" || create_client_status=$?
  if [ "$create_client_status" -ne 0 ] && [ ! -f "$create_attempt_file" ]; then
    echo "CreateResourcePool failed before the invoke fence; no create RPC was sent and activation may be retried." >&2
    cat "$grpc_stderr" >&2 || true
    exit 1
  fi
  if [ "$create_client_status" -eq 0 ]; then
    create_code=$grpc_code
  else
    create_code=ClientError
  fi
  case "$create_code" in
    OK)
      cp "$response_file" "$profile_file"
      validate_profile ""
      clear_create_attempt
      ;;
    Aborted|AlreadyExists|Canceled|ClientError|DataLoss|DeadlineExceeded|Internal|ResourceExhausted|Unavailable|Unknown)
      if [ "$create_code" = "ClientError" ]; then
        echo "CreateResourcePool client outcome is ambiguous; discovering the owner record without retrying the RPC" >&2
        cat "$grpc_stderr" >&2 || true
      else
        echo "CreateResourcePool returned gRPC $create_code; discovering the owner record without retrying the RPC" >&2
      fi
      discovery_deadline=$(( $(date +%s) + discovery_wait_seconds ))
      found=false
      while [ "$(date +%s)" -le "$discovery_deadline" ]; do
        if discover_pool; then
          validate_profile ""
          clear_create_attempt
          found=true
          break
        else
          discovery_status=$?
        fi
        if [ "$discovery_status" -ne 10 ] && [ "$discovery_status" -ne 75 ]; then
          exit 1
        fi
        sleep "$poll_interval"
      done
      if [ "$found" != true ]; then
        message="CreateResourcePool outcome is unresolved; the RPC was not retried. Rerun activation to rediscover before any new create."
        write_runtime_status "not_ready" "" "" "CREATE_OUTCOME_UNKNOWN" "" "$message"
        echo "$message" >&2
        exit 1
      fi
      ;;
    *)
      message="CreateResourcePool was rejected with gRPC $create_code after the invoke fence: $grpc_message. CP9 cannot prove that the owner made no side effect, so this session will refuse another Create; destroy and recreate it after reconciling tagged resources."
      write_runtime_status "not_ready" "" "" "CREATE_OUTCOME_UNKNOWN" "" "$message"
      echo "$message" >&2
      exit 1
      ;;
  esac
fi

shared_pool_id=$(profile_value id)

if [ "$mode" = "status" ]; then
  if get_pool "$shared_pool_id"; then
    profile_status=0
    write_profile_status || profile_status=$?
    [ "$profile_status" -eq 0 ] || [ "$profile_status" -eq 1 ] || exit 1
    exit 0
  fi
  exit 1
fi

python3 - "$shared_pool_id" "$organization_id" >"$strategy_payload" <<'PY'
import json
import sys

json.dump({
    "organizationId": sys.argv[2],
    "defaultResourcePoolId": sys.argv[1],
    "providerId": "AWS",
    "regionId": "AWS_US_WEST_2",
}, sys.stdout, separators=(",", ":"))
PY

deadline=$(( $(date +%s) + wait_seconds ))
while true; do
  if ! grpc_request UpdateOrgDefaultResourcePool "$strategy_payload"; then
    echo "UpdateOrgDefaultResourcePool gRPC client failed:" >&2
    cat "$grpc_stderr" >&2 || true
    exit 1
  fi
  if [ "$grpc_code" = "OK" ]; then
    break
  fi
  case "$grpc_code:$grpc_message" in
    NotFound:*Cluster.eks.aws.upbound.io*not\ found) ;;
    *)
      if ! is_retryable_grpc_code "$grpc_code"; then
        echo "UpdateOrgDefaultResourcePool failed with gRPC $grpc_code: $grpc_message" >&2
        exit 1
      fi
      ;;
  esac
  if [ "$(date +%s)" -gt "$deadline" ]; then
    echo "UpdateOrgDefaultResourcePool failed with gRPC $grpc_code: $grpc_message" >&2
    exit 1
  fi
  echo "UpdateOrgDefaultResourcePool returned transient gRPC $grpc_code; retrying" >&2
  sleep "$poll_interval"
done

python3 - "$response_file" "$shared_pool_id" "$organization_id" <<'PY'
import json
import pathlib
import sys

strategy = json.loads(pathlib.Path(sys.argv[1]).read_text())
if str(strategy.get("defaultResourcePoolId") or "") != sys.argv[2]:
    raise SystemExit("UpdateOrgDefaultResourcePool returned a different pool id")
if str(strategy.get("organizationId") or "") != sys.argv[3]:
    raise SystemExit("UpdateOrgDefaultResourcePool returned a different organization id")
PY

while [ "$(date +%s)" -le "$deadline" ]; do
  if get_pool "$shared_pool_id"; then
    :
  else
    get_status=$?
    if [ "$get_status" -ne 75 ]; then
      exit 1
    fi
    echo "GetResourcePool $shared_pool_id is temporarily unavailable; retrying" >&2
    sleep "$poll_interval"
    continue
  fi

  dataplane_name=$(profile_value dataplaneId)
  phase=$(profile_value lifecycleState)
  version=$(profile_value version)
  phase=${phase:-LIFECYCLE_STATE_UNSPECIFIED}
  echo "Essential V2 resource pool $shared_pool_id lifecycle=$phase dataplane=$dataplane_name version=$version"

  profile_status=0
  write_profile_status || profile_status=$?
  if [ "$profile_status" -eq 0 ]; then
    echo "Essential V2 resource pool $shared_pool_id is ACTIVE"
    exit 0
  fi
  [ "$profile_status" -eq 1 ] || exit 1

  case "$phase" in
    ACTIVE|CREATING|MODIFYING|RESUMING) ;;
    FAILED|PAUSING|PAUSED|LIFECYCLE_STATE_UNSPECIFIED)
      echo "Essential V2 resource pool $shared_pool_id reached unusable lifecycle $phase" >&2
      cat "$profile_file" >&2 || true
      exit 1
      ;;
    *)
      echo "Essential V2 resource pool $shared_pool_id returned unknown lifecycle $phase" >&2
      exit 1
      ;;
  esac
  sleep "$poll_interval"
done

echo "Timed out after ${wait_seconds}s waiting for Essential V2 resource pool $shared_pool_id to become ACTIVE" >&2
cat "$profile_file" >&2 || true
exit 1
