---
# Source: pwnedworker/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: pwnedworker
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
automountServiceAccountToken: false

---
# Source: pwnedworker/templates/secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: pwnedworker
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
type: Opaque
stringData:
  DJANGO_SECRET_KEY: "SUBSTITUA_openssl_rand_base64_48"
  VAULT_ENCRYPTION_KEY: "SUBSTITUA_openssl_rand_base64_32_urlsafe"
  DATABASE_URL: "postgresql://pwnedworker:SUBSTITUA_openssl_rand_hex_24@pwnedworker-postgres:5432/pwnedworker"
  POSTGRES_PASSWORD: "SUBSTITUA_openssl_rand_hex_24"
  INITIAL_ADMIN_USERNAME: "admin"
  INITIAL_ADMIN_PASSWORD: "SUBSTITUA_SENHA_FORTE"
  INITIAL_ADMIN_EMAIL: ""
  INITIAL_ADMIN_TENANT: "SUA_EMPRESA"

---
# Source: pwnedworker/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: pwnedworker
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
data:
  DJANGO_DEBUG: "0"
  DJANGO_ALLOWED_HOSTS: "SUBSTITUA.suaempresa.com.br"
  CELERY_BROKER_URL: "redis://pwnedworker-redis:6379/0"
  CELERY_RESULT_BACKEND: "redis://pwnedworker-redis:6379/1"
  HIBP_API_URL: "https://api.pwnedpasswords.com"
  HIBP_TIMEOUT_SECONDS: "5"
  BEYONDTRUST_VERIFY_TLS: "1"
  BEYONDTRUST_CHECKOUT_DURATION_MINUTES: "5"
  DOCS_URL: "https://pwnedworker.7dev.net.br/docs"

---
# Source: pwnedworker/templates/pvc-postgres.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pwnedworker-postgres
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi

---
# Source: pwnedworker/templates/service-postgres.yaml
apiVersion: v1
kind: Service
metadata:
  name: pwnedworker-postgres
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: postgres
spec:
  selector:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/component: postgres
  ports:
    - name: postgres
      port: 5432
      targetPort: postgres

---
# Source: pwnedworker/templates/service-redis.yaml
apiVersion: v1
kind: Service
metadata:
  name: pwnedworker-redis
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: redis
spec:
  selector:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/component: redis
  ports:
    - name: redis
      port: 6379
      targetPort: redis

---
# Source: pwnedworker/templates/service-web.yaml
apiVersion: v1
kind: Service
metadata:
  name: pwnedworker-web
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: web
spec:
  selector:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/component: web
  ports:
    - name: http
      port: 8000
      targetPort: http

---
# Source: pwnedworker/templates/deployment-postgres.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pwnedworker-postgres
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: postgres
spec:
  replicas: 1
  # "Recreate" (não "RollingUpdate"): só existe UM volume RWO — dois Pods do
  # Postgres tentando montá-lo ao mesmo tempo durante um rollout quebrariam.
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app.kubernetes.io/name: pwnedworker
      app.kubernetes.io/instance: pwnedworker
      app.kubernetes.io/component: postgres
  template:
    metadata:
      labels:
        app.kubernetes.io/name: pwnedworker
        app.kubernetes.io/instance: pwnedworker
        app.kubernetes.io/component: postgres
    spec:
      serviceAccountName: pwnedworker
      nodeSelector:
        kubernetes.io/arch: amd64
      containers:
        - name: postgres
          image: registry.7dev.net.br/pwnedworker/postgres:16-alpine
          ports:
            - name: postgres
              containerPort: 5432
          env:
            - name: POSTGRES_DB
              value: "pwnedworker"
            - name: POSTGRES_USER
              value: "pwnedworker"
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: pwnedworker
                  key: POSTGRES_PASSWORD
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "pwnedworker"]
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["pg_isready", "-U", "pwnedworker"]
            initialDelaySeconds: 15
            periodSeconds: 20
          resources:
            limits:
              cpu: 500m
              memory: 1Gi
            requests:
              cpu: 250m
              memory: 512Mi
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: pwnedworker-postgres

---
# Source: pwnedworker/templates/deployment-redis.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pwnedworker-redis
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: redis
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app.kubernetes.io/name: pwnedworker
      app.kubernetes.io/instance: pwnedworker
      app.kubernetes.io/component: redis
  template:
    metadata:
      labels:
        app.kubernetes.io/name: pwnedworker
        app.kubernetes.io/instance: pwnedworker
        app.kubernetes.io/component: redis
    spec:
      serviceAccountName: pwnedworker
      nodeSelector:
        kubernetes.io/arch: amd64
      containers:
        - name: redis
          image: registry.7dev.net.br/pwnedworker/redis:7-alpine
          ports:
            - name: redis
              containerPort: 6379
          readinessProbe:
            exec:
              command: ["redis-cli", "ping"]
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["redis-cli", "ping"]
            initialDelaySeconds: 10
            periodSeconds: 20
          resources:
            limits:
              cpu: 250m
              memory: 256Mi
            requests:
              cpu: 100m
              memory: 128Mi

---
# Source: pwnedworker/templates/deployment-web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pwnedworker-web
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: pwnedworker
      app.kubernetes.io/instance: pwnedworker
      app.kubernetes.io/component: web
  template:
    metadata:
      labels:
        app.kubernetes.io/name: pwnedworker
        app.kubernetes.io/instance: pwnedworker
        app.kubernetes.io/component: web
    spec:
      serviceAccountName: pwnedworker
      nodeSelector:
        kubernetes.io/arch: amd64
      # O entrypoint roda "migrate" logo no start e MORRE se o banco ainda não
      # aceita conexão. No Compose isso é resolvido por
      # "depends_on: condition: service_healthy"; no Kubernetes não há
      # equivalente, e sem este init o Pod entra em CrashLoopBackOff em toda
      # instalação nova, até o backoff chegar a 5 minutos.
      initContainers:
        - name: wait-for-db
          image: "registry.7dev.net.br/pwnedworker/app:0.1.9"
          imagePullPolicy: IfNotPresent
          command:
            - "sh"
            - "-c"
            - |
              until python -c "
              import os, django
              os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pwnedworker.settings')
              django.setup()
              from django.db import connection
              connection.ensure_connection()
              "; do echo "aguardando o banco aceitar conexao..."; sleep 3; done
          envFrom:
            - configMapRef:
                name: pwnedworker
            - secretRef:
                name: pwnedworker
      containers:
        - name: web
          image: "registry.7dev.net.br/pwnedworker/app:0.1.9"
          imagePullPolicy: IfNotPresent
          # Usa o entrypoint padrão da imagem (docker/entrypoint-web.sh):
          # migração + provisionamento do usuário inicial + Gunicorn.
          ports:
            - name: http
              containerPort: 8000
          envFrom:
            - configMapRef:
                name: pwnedworker
            - secretRef:
                name: pwnedworker
          # startupProbe protege a fase de inicialização: o entrypoint aplica
          # a migração e provisiona a conta inicial ANTES de o Gunicorn
          # escutar. Sem ela, a liveness (que começa a contar em 15s) mata o
          # container no meio da migração e o Pod nunca estabiliza. Enquanto
          # esta probe não passa, liveness e readiness ficam suspensas.
          # 30 tentativas x 5s = até 150s de margem para migrar.
          startupProbe:
            httpGet:
              path: /health
              port: http
              httpHeaders:
                - name: Host
                  value: SUBSTITUA.suaempresa.com.br
            periodSeconds: 5
            failureThreshold: 30
          # Readiness checa banco e Redis: falhando, o Pod sai do
          # balanceamento sem ser reiniciado.
          readinessProbe:
            httpGet:
              path: /ready
              port: http
              httpHeaders:
                - name: Host
                  value: SUBSTITUA.suaempresa.com.br
            initialDelaySeconds: 5
            periodSeconds: 10
          # Liveness NÃO toca dependência externa de propósito: se o banco
          # cair, reiniciar o container não resolve e só geraria laço de
          # restart.
          livenessProbe:
            httpGet:
              path: /health
              port: http
              httpHeaders:
                - name: Host
                  value: SUBSTITUA.suaempresa.com.br
            initialDelaySeconds: 15
            periodSeconds: 20
          resources:
            limits:
              cpu: 500m
              memory: 1Gi
            requests:
              cpu: 250m
              memory: 512Mi

---
# Source: pwnedworker/templates/deployment-worker.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pwnedworker-worker
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
    app.kubernetes.io/component: worker
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: pwnedworker
      app.kubernetes.io/instance: pwnedworker
      app.kubernetes.io/component: worker
  template:
    metadata:
      labels:
        app.kubernetes.io/name: pwnedworker
        app.kubernetes.io/instance: pwnedworker
        app.kubernetes.io/component: worker
    spec:
      serviceAccountName: pwnedworker
      nodeSelector:
        kubernetes.io/arch: amd64
      # O Kubernetes não tem "depends_on": Pods sobem em paralelo. Quem
      # aplica a migração é o entrypoint do Deployment "web", então sem isso
      # o worker pode começar a consumir a fila com o schema ainda
      # incompleto. "migrate --check" sai com código != 0 enquanto houver
      # migração pendente (e também enquanto o Postgres não aceitar conexão),
      # então o init trava aqui até o banco estar realmente pronto.
      initContainers:
        - name: wait-for-migrations
          image: "registry.7dev.net.br/pwnedworker/app:0.1.9"
          imagePullPolicy: IfNotPresent
          command:
            - "sh"
            - "-c"
            - "until python manage.py migrate --check; do echo 'aguardando migracoes do web...'; sleep 5; done"
          envFrom:
            - configMapRef:
                name: pwnedworker
            - secretRef:
                name: pwnedworker
      containers:
        - name: worker
          image: "registry.7dev.net.br/pwnedworker/app:0.1.9"
          imagePullPolicy: IfNotPresent
          # Sobrescreve o entrypoint padrão da imagem (que sobe o Gunicorn) —
          # mesmo padrão do serviço "worker" no docker-compose.prod.yml.
          command: ["celery"]
          args:
            - "-A"
            - "pwnedworker"
            - "worker"
            - "-l"
            - "info"
            - "--concurrency=4"
          envFrom:
            - configMapRef:
                name: pwnedworker
            - secretRef:
                name: pwnedworker
          livenessProbe:
            exec:
              command:
                - "celery"
                - "-A"
                - "pwnedworker"
                - "inspect"
                - "ping"
            initialDelaySeconds: 20
            periodSeconds: 30
            timeoutSeconds: 10
          resources:
            limits:
              cpu: 500m
              memory: 1Gi
            requests:
              cpu: 250m
              memory: 512Mi

---
# Source: pwnedworker/templates/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: pwnedworker
  labels:
    app.kubernetes.io/name: pwnedworker
    app.kubernetes.io/instance: pwnedworker
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: pwnedworker-0.1.0
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - SUBSTITUA.suaempresa.com.br
  rules:
    - host: SUBSTITUA.suaempresa.com.br
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: pwnedworker-web
                port:
                  name: http
