{{- if .Values.security.enabled }}
{{- include "gohoarder.validateSQLiteConfig" . }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "gohoarder.fullname" . }}-scanner
  labels:
    {{- include "gohoarder.scanner.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount.scanner }}
  selector:
    matchLabels:
      {{- include "gohoarder.scanner.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
        {{- with .Values.podAnnotations }}
        {{- toYaml . | nindent 8 }}
        {{- end }}
      labels:
        {{- include "gohoarder.scanner.selectorLabels" . | nindent 8 }}
    spec:
      {{- with .Values.global.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "gohoarder.serviceAccountName" . }}
      securityContext:
        {{- toYaml .Values.podSecurityContext | nindent 8 }}
      {{- if .Values.migration.enabled }}
      initContainers:
      # Wait for database to be ready
      - name: wait-for-db
        image: busybox:1.36
        command:
        - sh
        - -c
        - |
          echo "Waiting for database..."
          {{- if eq .Values.metadata.backend "postgresql" }}
          until nc -z {{ .Values.metadata.postgresql.host }} {{ .Values.metadata.postgresql.port }}; do
            echo "  PostgreSQL not ready, retrying in 2s..."
            sleep 2
          done
          echo "✓ PostgreSQL is ready"
          {{- else if eq .Values.metadata.backend "mysql" }}
          until nc -z {{ .Values.metadata.mysql.host }} {{ .Values.metadata.mysql.port }}; do
            echo "  MySQL not ready, retrying in 2s..."
            sleep 2
          done
          echo "✓ MySQL is ready"
          {{- else }}
          echo "✓ SQLite (no wait needed)"
          {{- end }}
        securityContext:
          allowPrivilegeEscalation: false
          runAsNonRoot: true
          runAsUser: 1000
        resources:
          limits:
            cpu: 100m
            memory: 64Mi
          requests:
            cpu: 10m
            memory: 32Mi
      # Run database migrations
      - name: migrate
        image: "{{ .Values.migration.image.repository }}:{{ .Values.migration.image.tag | default .Chart.AppVersion }}"
        imagePullPolicy: {{ .Values.migration.image.pullPolicy }}
        env:
        - name: DB_DRIVER
          value: {{ .Values.metadata.backend | quote }}
        {{- if eq .Values.metadata.backend "postgresql" }}
        - name: DATABASE_URL
          value: "postgresql://{{ .Values.metadata.postgresql.username }}:{{ .Values.metadata.postgresql.password }}@{{ .Values.metadata.postgresql.host }}:{{ .Values.metadata.postgresql.port }}/{{ .Values.metadata.postgresql.database }}?sslmode={{ .Values.metadata.postgresql.sslMode }}"
        {{- else if eq .Values.metadata.backend "mysql" }}
        - name: DATABASE_URL
          value: "{{ .Values.metadata.mysql.username }}:{{ .Values.metadata.mysql.password }}@tcp({{ .Values.metadata.mysql.host }}:{{ .Values.metadata.mysql.port }})/{{ .Values.metadata.mysql.database }}?charset={{ .Values.metadata.mysql.charset }}&parseTime={{ .Values.metadata.mysql.parseTime }}"
        {{- else }}
        - name: DATABASE_URL
          value: "/var/lib/gohoarder/metadata/gohoarder.db"
        {{- end }}
        args:
        - --driver=$(DB_DRIVER)
        - --dsn=$(DATABASE_URL)
        - --action=migrate
        - --log-level={{ .Values.migration.logLevel | default "info" }}
        - --timeout={{ .Values.migration.timeout | default "5m" }}
        securityContext:
          allowPrivilegeEscalation: false
          runAsNonRoot: true
          runAsUser: 1000
        resources:
          {{- toYaml .Values.migration.resources | nindent 10 }}
        {{- if eq .Values.metadata.backend "sqlite" }}
        volumeMounts:
        - name: metadata
          mountPath: /var/lib/gohoarder/metadata
        {{- end }}
      {{- end }}
      containers:
      - name: scanner
        securityContext:
          {{- toYaml .Values.securityContext | nindent 12 }}
        image: "{{ .Values.image.scanner.repository }}:{{ .Values.image.scanner.tag | default .Chart.AppVersion }}"
        imagePullPolicy: {{ .Values.image.scanner.pullPolicy }}
        env:
        - name: CONFIG_FILE
          value: /etc/gohoarder/config.yaml
        # Enable tool-based scanners only in scanner pod (server doesn't have the tools)
        - name: GOHOARDER_SECURITY_SCANNERS_TRIVY_ENABLED
          value: "{{ .Values.security.scanners.trivy.enabled }}"
        - name: GOHOARDER_SECURITY_SCANNERS_GRYPE_ENABLED
          value: "{{ .Values.security.scanners.grype.enabled }}"
        - name: GOHOARDER_SECURITY_SCANNERS_GOVULNCHECK_ENABLED
          value: "{{ .Values.security.scanners.govulncheck.enabled }}"
        - name: GOHOARDER_SECURITY_SCANNERS_NPM_AUDIT_ENABLED
          value: "{{ .Values.security.scanners.npmAudit.enabled }}"
        - name: GOHOARDER_SECURITY_SCANNERS_PIP_AUDIT_ENABLED
          value: "{{ .Values.security.scanners.pipAudit.enabled }}"
        {{- if and (eq .Values.metadata.backend "postgresql") .Values.metadata.postgresql.existingSecret }}
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: {{ .Values.metadata.postgresql.existingSecret }}
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Values.metadata.postgresql.existingSecret }}
              key: password
        {{- else if and (eq .Values.metadata.backend "postgresql") .Values.metadata.postgresql.username }}
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: {{ include "gohoarder.fullname" . }}-postgresql
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ include "gohoarder.fullname" . }}-postgresql
              key: password
        {{- end }}
        {{- if and (or (eq .Values.metadata.backend "mysql") (eq .Values.metadata.backend "mariadb")) .Values.metadata.mysql.existingSecret }}
        - name: MYSQL_USER
          valueFrom:
            secretKeyRef:
              name: {{ .Values.metadata.mysql.existingSecret }}
              key: username
        - name: MYSQL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Values.metadata.mysql.existingSecret }}
              key: password
        {{- else if and (or (eq .Values.metadata.backend "mysql") (eq .Values.metadata.backend "mariadb")) .Values.metadata.mysql.username }}
        - name: MYSQL_USER
          valueFrom:
            secretKeyRef:
              name: {{ include "gohoarder.fullname" . }}-mysql
              key: username
        - name: MYSQL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ include "gohoarder.fullname" . }}-mysql
              key: password
        {{- end }}
        {{- if and .Values.security.scanners.ghsa.enabled .Values.security.scanners.ghsa.existingSecret }}
        - name: GHSA_TOKEN
          valueFrom:
            secretKeyRef:
              name: {{ .Values.security.scanners.ghsa.existingSecret }}
              key: token
        {{- else if and .Values.security.scanners.ghsa.enabled .Values.security.scanners.ghsa.token }}
        - name: GHSA_TOKEN
          valueFrom:
            secretKeyRef:
              name: {{ include "gohoarder.fullname" . }}-ghsa
              key: token
        {{- end }}
        {{- with .Values.scanner.env }}
        {{- toYaml . | nindent 8 }}
        {{- end }}
        resources:
          {{- toYaml .Values.scanner.resources | nindent 12 }}
        volumeMounts:
        - name: config
          mountPath: /etc/gohoarder
          readOnly: true
        - name: storage
          mountPath: /var/cache/gohoarder
        - name: metadata
          mountPath: /var/lib/gohoarder/metadata
        {{- if .Values.security.scanners.trivy.enabled }}
        - name: trivy-cache
          mountPath: {{ .Values.security.scanners.trivy.cacheDb }}
        {{- end }}
        - name: tmp
          mountPath: /tmp
      volumes:
      - name: config
        configMap:
          name: {{ include "gohoarder.fullname" . }}-config
      {{- include "gohoarder.storageVolume" . | nindent 6 }}
      {{- include "gohoarder.metadataVolume" . | nindent 6 }}
      {{- include "gohoarder.trivyCacheVolume" . | nindent 6 }}
      - name: tmp
        emptyDir: {}
      {{- with .Values.scanner.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.scanner.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.scanner.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
{{- end }}
