{{- $frontend := .Values.frontend }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "infisical.frontend.fullname" . }}
  annotations:
    updatedAt: {{ now | date "2006-01-01 MST 15:04:05" | quote }}
  {{- with .Values.frontend.deploymentAnnotations }}
    {{- toYaml . | nindent 4 }}
  {{- end }}
  labels:
    {{- include "infisical.frontend.labels" . | nindent 4 }}
spec:
  replicas: {{ $frontend.replicaCount }}
  selector:
    matchLabels:
      {{- include "infisical.frontend.matchLabels" . | nindent 6 }}
  template:
    metadata: 
      labels:
        {{- include "infisical.frontend.matchLabels" . | nindent 8 }}
      annotations:
        updatedAt: {{ now | date "2006-01-01 MST 15:04:05" | quote }}
        {{- with $frontend.podAnnotations }}
        {{- toYaml . | nindent 8 }}
        {{- end }}
    spec:
      containers:
      - name: {{ template "infisical.name" . }}-{{ $frontend.name }}
        image: "{{ $frontend.image.repository }}:{{ $frontend.image.tag | default "latest" }}"
        imagePullPolicy: {{ $frontend.image.pullPolicy }}
        readinessProbe:
          httpGet:
            path: /
            port: 3000
          initialDelaySeconds: 10
          periodSeconds: 10
        envFrom:
        - secretRef:
            name: {{ $frontend.kubeSecretRef | default (include "infisical.frontend.fullname" .)  }}
        ports: 
        - containerPort: 3000

---

apiVersion: v1
kind: Service 
metadata:
  name: {{ include "infisical.frontend.fullname" . }}
  labels:
    {{- include "infisical.frontend.labels" . | nindent 4 }}
  {{- with $frontend.service.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
  type: {{ $frontend.service.type }}
  selector:
    {{- include "infisical.frontend.matchLabels" . | nindent 8 }}
  ports:
    - protocol: TCP
      port: 3000 # service
      targetPort: 3000 # container port 
      {{- if eq $frontend.service.type "NodePort" }}
      nodePort: {{ $frontend.service.nodePort }}
      {{- end }}

---

{{ if not $frontend.kubeSecretRef }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "infisical.frontend.fullname" . }}
  annotations:
    "helm.sh/resource-policy": "keep"
type: Opaque
stringData:
  {{- $requiredVars := dict }}
  {{- $secretObj := (lookup "v1" "Secret" .Release.Namespace (include "infisical.frontend.fullname" .)) | default dict }}
  {{- $secretData := (get $secretObj "data") | default dict }}
  {{ range $key, $value := .Values.frontendEnvironmentVariables }}
    {{- $default := get $requiredVars $key -}}
    {{- $current := get $secretData $key | b64dec -}}
    {{- $v := $value | default ($current | default $default) -}}
    {{ $key }}: {{ $v | quote }}
  {{ end -}}
{{- end }}