#!/usr/bin/env sh
set -eu

# Longhorn blocks direct CR patches for some settings; use the internal API instead.

api_base="http://longhorn-backend.longhorn-system.svc:9500/v1/settings"
curl_opts="-fsS --connect-timeout 3 --max-time 15"

wait_for_api() {
  attempts=30
  while [ "${attempts}" -gt 0 ]; do
    if curl ${curl_opts} "${api_base}" >/dev/null 2>&1; then
      return 0
    fi
    attempts=$((attempts - 1))
    sleep 2
  done
  echo "Longhorn API not ready after retries." >&2
  return 1
}

update_setting() {
  name="$1"
  value="$2"

  current="$(curl ${curl_opts} "${api_base}/${name}" || true)"
  if echo "${current}" | grep -Fq "\"value\":\"${value}\""; then
    echo "Setting ${name} already set."
    return 0
  fi

  echo "Setting ${name} -> ${value}"
  out="$(mktemp)"
  if curl ${curl_opts} -o "${out}" -X PUT \
    -H "Content-Type: application/json" \
    -d "{\"value\":\"${value}\"}" \
    "${api_base}/${name}"; then
    rm -f "${out}"
    return 0
  fi

  current="$(curl ${curl_opts} "${api_base}/${name}" || true)"
  if echo "${current}" | grep -Fq "\"value\":\"${value}\""; then
    echo "Setting ${name} stored; Longhorn will apply it when current state allows."
    rm -f "${out}"
    return 0
  fi

  cat "${out}" >&2 || true
  rm -f "${out}"
  return 1
}

wait_for_api
update_setting default-engine-image "registry.bstein.dev/infra/longhorn-engine:v1.8.2"
update_setting default-instance-manager-image "registry.bstein.dev/infra/longhorn-instance-manager:v1.8.2"
update_setting default-backing-image-manager-image "registry.bstein.dev/infra/longhorn-backing-image-manager:v1.8.2"
update_setting support-bundle-manager-image "registry.bstein.dev/infra/longhorn-support-bundle-kit:v0.0.56"
update_setting taint-toleration "veles.bstein.dev/simulation=true:NoSchedule"
# Keep storage-heavy nodes from getting hammered by rebuild storms and skew.
update_setting replica-auto-balance "best-effort"
update_setting concurrent-replica-rebuild-per-node-limit "2"
update_setting node-down-pod-deletion-policy "delete-both-statefulset-and-deployment-pod"
