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

release_name="longhorn"
release_namespace="longhorn-system"
selector="app.kubernetes.io/instance=${release_name}"

annotate_and_label() {
  local scope="$1"
  local kind="$2"
  if [ "${scope}" = "namespaced" ]; then
    kubectl -n "${release_namespace}" annotate "${kind}" -l "${selector}" \
      meta.helm.sh/release-name="${release_name}" \
      meta.helm.sh/release-namespace="${release_namespace}" \
      --overwrite >/dev/null 2>&1 || true
    kubectl -n "${release_namespace}" label "${kind}" -l "${selector}" \
      app.kubernetes.io/managed-by=Helm --overwrite >/dev/null 2>&1 || true
  else
    kubectl annotate "${kind}" -l "${selector}" \
      meta.helm.sh/release-name="${release_name}" \
      meta.helm.sh/release-namespace="${release_namespace}" \
      --overwrite >/dev/null 2>&1 || true
    kubectl label "${kind}" -l "${selector}" \
      app.kubernetes.io/managed-by=Helm --overwrite >/dev/null 2>&1 || true
  fi
}

namespaced_kinds=(
  configmap
  service
  serviceaccount
  deployment
  daemonset
  job
  role
  rolebinding
)

cluster_kinds=(
  clusterrole
  clusterrolebinding
  customresourcedefinition
  priorityclass
)

for kind in "${namespaced_kinds[@]}"; do
  annotate_and_label "namespaced" "${kind}"
done

for kind in "${cluster_kinds[@]}"; do
  annotate_and_label "cluster" "${kind}"
done
