# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

{{- if .Values.cartService.create }}
{{- if .Values.serviceAccounts.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{.Release.Namespace}}
  {{- with .Values.serviceAccounts.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
---
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ .Values.cartService.name }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.cartService.name }}
  template:
    metadata:
      {{- if .Values.cartDatabase.externalRedisTlsOrigination.enable }}
      annotations:
        sidecar.istio.io/userVolumeMount: '[{"name": "{{ .Values.cartDatabase.externalRedisTlsOrigination.name }}", "mountPath": "/etc/certs", "readonly": true}]'
        sidecar.istio.io/userVolume: '[{"name": "{{ .Values.cartDatabase.externalRedisTlsOrigination.name }}", "secret": {"secretName": "{{ .Values.cartDatabase.externalRedisTlsOrigination.name }}"}}]'
        proxy.istio.io/config: '{"holdApplicationUntilProxyStarts": true}'
      {{- end }}
      labels:
        app: {{ .Values.cartService.name }}
    spec:
      {{- if .Values.serviceAccounts.create }}
      serviceAccountName: {{ .Values.cartService.name }}
      {{- else }}
      serviceAccountName: default
      {{- end }}
      terminationGracePeriodSeconds: 5
      {{- if .Values.securityContext.enable }}
      securityContext:
        fsGroup: 1000
        runAsGroup: 1000
        runAsNonRoot: true
        runAsUser: 1000
      {{- end }}
        {{- if .Values.seccompProfile.enable }}
        seccompProfile:
          type: {{ .Values.seccompProfile.type }}
        {{- end }}
      containers:
      - name: server
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            drop:
              - ALL
          privileged: false
          readOnlyRootFilesystem: true
        image: {{ .Values.images.repository }}/{{ .Values.cartService.name }}:{{ .Values.images.tag | default .Chart.AppVersion }}
        ports:
        - containerPort: 7070
        env:
        {{- if eq .Values.cartDatabase.type "spanner" }}
        - name: SPANNER_CONNECTION_STRING
        {{- else }}
        - name: REDIS_ADDR
        {{- end }}
          value: {{ .Values.cartDatabase.connectionString | quote }}
        resources:
          {{- toYaml .Values.cartService.resources | nindent 10 }}
        readinessProbe:
          initialDelaySeconds: 15
          grpc:
            port: 7070
        livenessProbe:
          initialDelaySeconds: 15
          periodSeconds: 10
          grpc:
            port: 7070
---
apiVersion: v1
kind: Service
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ .Values.cartService.name }}
spec:
  type: ClusterIP
  selector:
    app: {{ .Values.cartService.name }}
  ports:
  - name: grpc
    port: 7070
    targetPort: 7070
{{- if .Values.networkPolicies.create }}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{ .Release.Namespace }}
spec:
  podSelector:
    matchLabels:
      app: {{ .Values.cartService.name }}
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: {{ .Values.frontend.name }}
    - podSelector:
        matchLabels:
          app: {{ .Values.checkoutService.name }}
    ports:
     - port: 7070
       protocol: TCP
  egress:
  - {}
{{- end }}
{{- if .Values.sidecars.create }}
---
apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{ .Release.Namespace }}
spec:
  workloadSelector:
    labels:
      app: {{ .Values.cartService.name }}
  egress:
  - hosts:
    - istio-system/*
    {{- if eq .Values.cartDatabase.type "redis" }}
    {{- if .Values.cartDatabase.externalRedisTlsOrigination.enable }}
    - ./{{ .Values.cartDatabase.externalRedisTlsOrigination.name }}.{{ .Release.Namespace }}
    {{- else }}
    - ./{{ .Values.cartDatabase.inClusterRedis.name }}.{{ .Release.Namespace }}.svc.cluster.local
    {{- end }}
    {{- end }}
    {{- if .Values.opentelemetryCollector.create }}
    - ./{{ .Values.opentelemetryCollector.name }}.{{ .Release.Namespace }}.svc.cluster.local
    {{- end }}
{{- end }}
{{- if .Values.authorizationPolicies.create }}
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: {{ .Values.cartService.name }}
  namespace: {{ .Release.Namespace }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.cartService.name }}
  rules:
  - from:
    - source:
        principals:
        {{- if .Values.serviceAccounts.create }}
        - cluster.local/ns/{{ .Release.Namespace }}/sa/{{ .Values.frontend.name }}
        - cluster.local/ns/{{ .Release.Namespace }}/sa/{{ .Values.checkoutService.name }}
        {{- else }}
        - cluster.local/ns/{{ .Release.Namespace }}/sa/default
        {{- end }}
    to:
    - operation:
        paths:
        - /hipstershop.CartService/AddItem
        - /hipstershop.CartService/GetCart
        - /hipstershop.CartService/EmptyCart
        methods:
        - POST
        ports:
        - "7070"
{{- end }}

{{- if .Values.cartDatabase.inClusterRedis.create }}
---
{{- if .Values.serviceAccounts.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{.Release.Namespace}}
  {{- if not .Values.serviceAccounts.annotationsOnlyForCartservice }}
  {{- with .Values.serviceAccounts.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  {{- end }}
---
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{ .Release.Namespace }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.cartDatabase.inClusterRedis.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.cartDatabase.inClusterRedis.name }}
    spec:
      {{- if .Values.serviceAccounts.create }}
      serviceAccountName: {{ .Values.cartDatabase.inClusterRedis.name }}
      {{- else }}
      serviceAccountName: default
      {{- end }}
      {{- if .Values.securityContext.enable }}
      securityContext:
        fsGroup: 1000
        runAsGroup: 1000
        runAsNonRoot: true
        runAsUser: 1000
        {{- if .Values.seccompProfile.enable }}
        seccompProfile:
          type: {{ .Values.seccompProfile.type }}
        {{- end }}
      {{- end }}
      containers:
      - name: redis
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            drop:
              - ALL
          privileged: false
          readOnlyRootFilesystem: true
        {{- if .Values.cartDatabase.inClusterRedis.publicRepository }}
        image: redis:alpine@sha256:02419de7eddf55aa5bcf49efb74e88fa8d931b4d77c07eff8a6b2144472b6952
        {{- else }}
        image: {{ .Values.images.repository }}/redis:alpine
        {{- end }}
        ports:
        - containerPort: 6379
        readinessProbe:
          periodSeconds: 5
          tcpSocket:
            port: 6379
        livenessProbe:
          periodSeconds: 5
          tcpSocket:
            port: 6379
        volumeMounts:
        - mountPath: /data
          name: redis-data
        resources:
          limits:
            memory: 256Mi
            cpu: 125m
          requests:
            cpu: 70m
            memory: 200Mi
      volumes:
      - name: redis-data
        emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{ .Release.Namespace }}
spec:
  type: ClusterIP
  selector:
    app: {{ .Values.cartDatabase.inClusterRedis.name }}
  ports:
  - name: tcp-redis
    port: 6379
    targetPort: 6379
{{- if .Values.networkPolicies.create }}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{ .Release.Namespace }}
spec:
  podSelector:
    matchLabels:
      app: {{ .Values.cartDatabase.inClusterRedis.name }}
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: {{ .Values.cartService.name }}
    ports:
     - port: 6379
       protocol: TCP
  egress:
  - {}
{{- end }}
{{- if .Values.sidecars.create }}
---
apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{ .Release.Namespace }}
spec:
  workloadSelector:
    labels:
      app: {{ .Values.cartDatabase.inClusterRedis.name }}
  egress:
  - hosts:
    - istio-system/*
{{- end }}
{{- if .Values.authorizationPolicies.create }}
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: {{ .Values.cartDatabase.inClusterRedis.name }}
  namespace: {{ .Release.Namespace }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.cartDatabase.inClusterRedis.name }}
  rules:
  - from:
    - source:
        principals:
        {{- if .Values.serviceAccounts.create }}
        - cluster.local/ns/{{ .Release.Namespace }}/sa/{{ .Values.cartService.name }}
        {{- else }}
        - cluster.local/ns/{{ .Release.Namespace }}/sa/default
        {{- end }}
    to:
    - operation:
        ports:
        - "6379"
{{- end }}
{{- end }}
{{- if .Values.cartDatabase.externalRedisTlsOrigination.enable }}
---
apiVersion: v1
data:
  {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}.pem: {{ .Values.cartDatabase.externalRedisTlsOrigination.certificate | b64enc | quote }}
kind: Secret
metadata:
  name: {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}
  namespace: {{ .Release.Namespace }}
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}
  namespace: {{ .Release.Namespace }}
spec:
  exportTo:
  - '.'
  host: {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}.{{ .Release.Namespace }}
  trafficPolicy:
    tls:
      mode: SIMPLE
      caCertificates: /etc/certs/{{ .Values.cartDatabase.externalRedisTlsOrigination.name }}.pem
---
apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
  name: {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}
  namespace: {{ .Release.Namespace }}
spec:
  hosts:
  - {{ .Values.cartDatabase.externalRedisTlsOrigination.name }}.{{ .Release.Namespace }}
  addresses:
  - {{ .Values.cartDatabase.externalRedisTlsOrigination.endpointAddress }}/32
  endpoints:
  - address: {{ .Values.cartDatabase.externalRedisTlsOrigination.endpointAddress }}
  location: MESH_EXTERNAL
  resolution: STATIC
  ports:
  - number: {{ .Values.cartDatabase.externalRedisTlsOrigination.endpointPort }}
    name: tcp-redis
    protocol: TCP
{{- end }}
{{- end }}
