{{- if .Values.ingressRedirects.enabled }}
{{- $fullName := include "impress.fullname" . -}}
{{- $ns := .Release.Namespace -}}

{{- range $i, $r := .Values.ingressRedirects.rules }}
{{- $host := $r.host | default $.Values.ingressRedirects.host -}}
{{- $from := $r.from | default "/home" -}}
{{- $to := required (printf "ingressRedirects.rules[%d].to is required" $i) $r.to -}}
{{- $name := printf "%s-redirect-%s" $fullName (replace "/" "-" (trimAll "/" $from)) | trunc 63 | trimSuffix "-" -}}
{{- if $i }}
---
{{- end }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ $name }}
  namespace: {{ $ns }}
  annotations:
    {{- if or (not $r.code) (eq (toString $r.code) "301") }}
    nginx.ingress.kubernetes.io/permanent-redirect: "{{ $to }}"
    {{- else }}
    nginx.ingress.kubernetes.io/temporal-redirect: "{{ $to }}"
    nginx.ingress.kubernetes.io/temporal-redirect-code: "{{ $r.code }}"
    {{- end }}
spec:
  {{- if $.Values.ingressRedirects.className }}
  ingressClassName: {{ $.Values.ingressRedirects.className }}
  {{- end }}
  {{- if $.Values.ingressRedirects.tls.enabled }}
  tls:
    {{- if $host }}
    - secretName: {{ $.Values.ingressRedirects.tls.secretName | default (printf "%s-tls" $fullName) | quote }}
      hosts:
        - {{ $host | quote }}
    {{- end }}
    {{- range $.Values.ingressRedirects.tls.additional }}
    - hosts:
        {{- range .hosts }}
        - {{ . | quote }}
        {{- end }}
      secretName: {{ .secretName }}
    {{- end }}
  {{- end }}
  rules:
  - host: {{ $host }}
    http:
      paths:
      - path: {{ $from }}
        pathType: Exact
        backend:
          service:
            name: {{ include "impress.frontend.fullname" $ }}
            port:
              number: {{ $.Values.frontend.service.port }}
      - path: {{ printf "%s/" (trimSuffix "/" $from) }}
        pathType: Exact
        backend:
          service:
            name: {{ include "impress.frontend.fullname" $ }}
            port:
              number: {{ $.Values.frontend.service.port }}
{{- end }}
{{- end }}
