{{/* vim: set filetype=mustache: */}}

{{/*
Create the name of the pod name to use in prometheus queries
*/}}
{{- define "defaultTemplates.podname" -}}
{{ .Values.rolloutStrategy.deploymentName }}
{{- end -}}

{{/*
Define the address of the prometheus server to be used in the default AnalysisTemplates
*/}}
{{- define "defaultTemplates.basicTemplates.promServerAdress" -}}
{{ .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.promServerAddress }}
{{- end -}}

{{- define "promAuthSecretName" -}}
{{- include "defaultTemplates.podname" . }}-prom-auth
{{- end -}}

{{- define "defaultTemplates.basicTemplates.prometheusProvider" -}}
prometheus:
{{- if .Values.rolloutAnalysisTemplates.authToken }}
  headers:
  - key: Authorization
    value: {{ "Bearer {{" }} {{ "args.prom-auth-token" }} {{ "}}" }}
{{- end }}
  address: {{ .Template.promServerAddress | default .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.promServerAddress }}
{{- end -}}

{{- define "memoryUsageTemplate.name" -}}jfrog-memory-usage-analysis{{- end -}}

{{- define "memoryUsageTemplate.provider" -}}
{{ include "defaultTemplates.basicTemplates.prometheusProvider" . }}
  query: {{ include "memoryUsageTemplate.query" . | quote }}
{{- end -}}

{{- define "cpuUsageTemplate.name" -}}jfrog-cpu-usage-analysis{{- end -}}

{{- define "cpuUsageTemplate.provider" -}}
{{ include "defaultTemplates.basicTemplates.prometheusProvider" . }}
  query: {{ include "cpuUsageTemplate.query" . | quote }}
{{- end -}}

{{/*
Define the prometheus queries to be used in the default AnalysisTemplates
*/}}
{{- define "memoryUsageTemplate.query" -}}
avg( sum by (namespace, pod) (container_memory_working_set_bytes{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) and on(namespace, pod) max by (namespace, pod) (kube_pod_labels{label_role="canary"}) ) / avg( sum by (namespace, pod) (container_memory_working_set_bytes{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) and on(namespace, pod) max by (namespace, pod) (kube_pod_labels{label_role="stable"}) )
{{- end -}}
{{- define "cpuUsageTemplate.query" -}}
avg( sum by (namespace, pod) (node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) and on(namespace, pod) max by (namespace, pod) (kube_pod_labels{label_role="canary"}) ) / avg( sum by (namespace, pod) (node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) and on(namespace, pod) max by (namespace, pod) (kube_pod_labels{label_role="stable"}) )
{{- end -}}

{{- define "canaryJobTemplateName" -}}
{{ .Release.Name }}-canary-job
{{- end -}}

{{- define "canarySecretName" -}}
{{ .Release.Name }}-canary-secret
{{- end -}}

{{- define "renderCanarySteps" -}}
{{- $root := . -}}
{{- $steps := .Values.rolloutStrategy.canary.steps -}}
{{- $canary_region := .Values.canaryRegion -}}
{{- $canary_service_name := .Values.canaryServiceName -}}
{{- range $i, $step := $steps }}
  {{- if $step.setAccountWeight }}
    {{- $account_type := $step.setAccountWeight.type -}}
    {{- $weight := $step.setAccountWeight.weight -}}
    {{- $interval := (or $step.setAccountWeight.interval 10) -}}
    {{- $timeout := (or $step.setAccountWeight.timeout 7200) -}}
    {{- if not (and $account_type $weight) }}
      {{- fail (printf "Missing required fields in setAccountWeight step at index %d, required fields: [account_type, weight]" $i) }}
    {{- end }}
    {{- if not (or (eq (int $weight) 20) (eq (int $weight) 40) (eq (int $weight) 100)) }}
      {{- fail (printf "Invalid weight value '%v' in canary-request step at index %d, allowed values: [20, 40, 100]" $weight $i) }}
    {{- end }}
    {{- if not (and $canary_service_name $canary_region) }}
      {{- fail "Missing required values: canary_service_name and/or canary_region" }}
    {{- end }}
- analysis:
    args:
      - name: service
        value: {{ $canary_service_name | quote }}
      - name: account_type
        value: {{ $account_type | quote }}
      - name: weight
        value: {{ $weight | quote }}
      - name: region
        value: {{ $canary_region | quote }}
      - name: interval
        value: {{ $interval | quote }}
      - name: timeout
        value: {{ $timeout | quote }}
    templates:
      - templateName: {{ include "canaryJobTemplateName" $root }}
  {{- else }}
- {{ toYaml $step | nindent 2 | trim }}
  {{- end }}
{{- end }}
{{- end -}}

{{/*
Generate image pull secret name from registry URL
Extracts registry from image URL (e.g., "x.jfrog.io/path:tag" -> "x.jfrog.io")
Converts to pull secret format (e.g., "x.jfrog.io" -> "x-jfrog-io-pull-secret")
*/}}
{{- define "jfrog-argo-rollouts.registryPullSecretName" -}}
{{- $image := .Values.canaryRequestJobImage -}}
{{- $parts := splitList "/" $image -}}
{{- $registry := (index $parts 0) -}}
{{- $secretName := ($registry | replace "." "-") -}}
{{- printf "%s-pull-secret" $secretName -}}
{{- end -}}

{{/*
JSON request body for the Coralogix Cases API, used by the coralogixAlertsTemplate basic template.
Filters (all server-side): namespace via groupings key=<namespaceGroupingKey, default "kubernetes.namespace">
= .Release.Namespace; service via labels key=<serviceLabelKey, default "serviceName">
= <canaryServiceName with any "mt_" prefix stripped>; and statuses (default ["CASE_STATUS_ACTIVE"]).
Built with toJson so values are escaped correctly.
*/}}
{{- define "coralogixAlertsTemplate.body" -}}
{{- $cfg := .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.templates.coralogixAlertsTemplate -}}
{{- $service := .Values.canaryServiceName | trimPrefix "mt_" -}}
{{- $filters := dict
  "groupings" (list (dict "key" ($cfg.namespaceGroupingKey | default "kubernetes.namespace") "values" (list .Release.Namespace)))
  "labels" (list (dict "key" ($cfg.serviceLabelKey | default "serviceName") "values" (list $service)))
  "statuses" ($cfg.statuses | default (list "CASE_STATUS_ACTIVE")) -}}
{{- dict "filters" $filters | toJson -}}
{{- end -}}

{{/*
Web provider block for the Coralogix alerts template. POSTs to the Coralogix Cases API; namespace,
service and status are all filtered server-side (see coralogixAlertsTemplate.body), so the response
contains only the current service's active cases in this namespace and the template simply gates on
len(result). jsonPath targets the cases array node (responseJsonPath, default {$.cases}) so the idle
case is an empty array (len 0 -> pass) rather than erroring "web metric produced no value". Uses the
per-template promServerAddress (fallback to group) + casesApiPath, and the shared Bearer authToken.
*/}}
{{- define "coralogixAlertsTemplate.provider" -}}
{{- $cfg := .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.templates.coralogixAlertsTemplate -}}
{{- $address := $cfg.promServerAddress | default .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.promServerAddress -}}
{{- $path := $cfg.casesApiPath | default "/mgmt/openapi/5/cases/cases/v1" -}}
web:
  method: POST
  url: {{ printf "%s%s" (trimSuffix "/" $address) $path | quote }}
  headers:
    - key: Content-Type
      value: application/json
{{- if .Values.rolloutAnalysisTemplates.authToken }}
    - key: Authorization
      value: "Bearer {{ "{{" }} args.prom-auth-token {{ "}}" }}"
{{- end }}
  body: {{ include "coralogixAlertsTemplate.body" . | quote }}
  jsonPath: {{ $cfg.responseJsonPath | default "{$.cases}" | quote }}
{{- end -}}
