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

# Idempotent source-of-truth for AWOOOI ArgoCD health persistence.
# Keeps Application child resource health visible and prevents the old global
# /status ignore rule from making top-level health look degraded/opaque.

NAMESPACE="${NAMESPACE:-argocd}"
CM_NAME="${CM_NAME:-argocd-cm}"
PARAMS_CM_NAME="${PARAMS_CM_NAME:-argocd-cmd-params-cm}"

changed=0

get_jsonpath() {
  kubectl -n "${NAMESPACE}" get cm "$1" -o "jsonpath=$2" 2>/dev/null || true
}

ignore_all_value="$(get_jsonpath "${CM_NAME}" "{.data.resource\\.customizations\\.ignoreResourceUpdates\\.all}")"
if [[ -n "${ignore_all_value}" ]]; then
  echo "remove ${CM_NAME}.data.resource.customizations.ignoreResourceUpdates.all"
  kubectl -n "${NAMESPACE}" patch cm "${CM_NAME}" \
    --type=json \
    -p='[{"op":"remove","path":"/data/resource.customizations.ignoreResourceUpdates.all"}]'
  changed=1
else
  echo "ok ${CM_NAME}: no global /status ignore"
fi

persist_value="$(get_jsonpath "${PARAMS_CM_NAME}" "{.data.controller\\.resource\\.health\\.persist}")"
if [[ "${persist_value}" != "true" ]]; then
  echo "set ${PARAMS_CM_NAME}.data.controller.resource.health.persist=true"
  kubectl -n "${NAMESPACE}" patch cm "${PARAMS_CM_NAME}" \
    --type=merge \
    -p='{"data":{"controller.resource.health.persist":"true"}}'
  changed=1
else
  echo "ok ${PARAMS_CM_NAME}: controller.resource.health.persist=true"
fi

if [[ "${changed}" == "1" ]]; then
  echo "restart ArgoCD control-plane to load health config"
  kubectl -n "${NAMESPACE}" rollout restart deploy/argocd-redis
  kubectl -n "${NAMESPACE}" rollout restart deploy/argocd-server
  kubectl -n "${NAMESPACE}" rollout restart statefulset/argocd-application-controller
  kubectl -n "${NAMESPACE}" rollout status deploy/argocd-redis --timeout=180s
  kubectl -n "${NAMESPACE}" rollout status deploy/argocd-server --timeout=180s
  kubectl -n "${NAMESPACE}" rollout status statefulset/argocd-application-controller --timeout=180s
else
  echo "no change"
fi

kubectl -n "${NAMESPACE}" get cm "${CM_NAME}" "${PARAMS_CM_NAME}" \
  -o jsonpath='{range .items[*]}{.metadata.name}{": ignore-all="}{.data.resource\.customizations\.ignoreResourceUpdates\.all}{", health-persist="}{.data.controller\.resource\.health\.persist}{"\n"}{end}'
