# Umami v3 - Privacy-focused web analytics for felhom.eu
# Dashboard: https://stats.felhom.eu
# Tracking: Add <script> tag to website HTML pages (see bottom of file)
#
# Umami v3 requires PostgreSQL (no SQLite/MySQL support).
# This manifest deploys a dedicated small PostgreSQL instance alongside Umami
# to keep it self-contained within the felhom-system namespace.
#
# PREREQUISITES:
#   1. Create the Secret with credentials:
#      APP_SECRET: Random string for session encryption (generate with: openssl rand -hex 32)
#      POSTGRES_PASSWORD: Database password (generate with: openssl rand -hex 16)
#
#      kubectl create secret generic umami-config \
#        --namespace=felhom-system \
#        --from-literal=APP_SECRET="$(openssl rand -hex 32)" \
#        --from-literal=POSTGRES_PASSWORD="$(openssl rand -hex 16)"
#
#   2. Apply this manifest:
#      kubectl apply -f umami.yaml
#
#   3. Wait for pods to be ready (~30-60 seconds for first start, DB init):
#      kubectl get pods -n felhom-system -l app=umami -w
#      kubectl get pods -n felhom-system -l app=umami-db -w
#
#   4. Login at https://stats.felhom.eu
#      Default credentials: admin / umami
#      ⚠️  CHANGE THE PASSWORD IMMEDIATELY after first login!
#
#   5. Add your website in Umami:
#      Settings → Websites → Add website → Name: "felhom.eu", Domain: "felhom.eu"
#      Copy the tracking code and add it to your HTML pages (see bottom of file).
#
# DEBUGGING:
#   kubectl logs -n felhom-system deploy/umami -f
#   kubectl logs -n felhom-system deploy/umami-db -f
#   kubectl exec -it -n felhom-system deploy/umami -- wget -qO- http://localhost:3000/api/heartbeat
#   kubectl exec -it -n felhom-system deploy/umami-db -- pg_isready -U umami
#
# BACKUP:
#   # Dump the database:
#   kubectl exec -n felhom-system deploy/umami-db -- pg_dump -U umami umami > umami-backup-$(date +%Y%m%d).sql
#   # Restore:
#   cat umami-backup-YYYYMMDD.sql | kubectl exec -i -n felhom-system deploy/umami-db -- psql -U umami umami

# =============================================================================
# PERSISTENT STORAGE
# =============================================================================
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: umami-db-data
  namespace: felhom-system
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: longhorn
  resources:
    requests:
      storage: 2Gi

# =============================================================================
# POSTGRESQL - Dedicated database for Umami
# =============================================================================
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: umami-db
  namespace: felhom-system
  labels:
    app: umami-db
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: umami-db
  template:
    metadata:
      labels:
        app: umami-db
    spec:
      containers:
        - name: postgres
          image: postgres:16-alpine
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
              value: "umami"
            - name: POSTGRES_USER
              value: "umami"
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: umami-config
                  key: POSTGRES_PASSWORD
            - name: PGDATA
              value: "/var/lib/postgresql/data/pgdata"
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
          resources:
            requests:
              memory: "64Mi"
              cpu: "25m"
            limits:
              memory: "256Mi"
              cpu: "500m"
          livenessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - umami
            initialDelaySeconds: 15
            periodSeconds: 30
          readinessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - umami
            initialDelaySeconds: 5
            periodSeconds: 10
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: umami-db-data
---
apiVersion: v1
kind: Service
metadata:
  name: umami-db
  namespace: felhom-system
spec:
  selector:
    app: umami-db
  ports:
    - port: 5432
      targetPort: 5432

# =============================================================================
# UMAMI - Web Analytics Application
# =============================================================================
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: umami
  namespace: felhom-system
  labels:
    app: umami
spec:
  replicas: 1
  selector:
    matchLabels:
      app: umami
  template:
    metadata:
      labels:
        app: umami
    spec:
      # Wait for DB to be available before starting Umami
      initContainers:
        - name: wait-for-db
          image: postgres:16-alpine
          command:
            - sh
            - -c
            - |
              echo "Waiting for PostgreSQL to be ready..."
              until pg_isready -h umami-db -p 5432 -U umami; do
                echo "  ...still waiting"
                sleep 2
              done
              echo "PostgreSQL is ready!"
          resources:
            requests:
              memory: "16Mi"
              cpu: "5m"
            limits:
              memory: "32Mi"
              cpu: "50m"
      containers:
        - name: umami
          image: ghcr.io/umami-software/umami:postgresql-latest
          ports:
            - containerPort: 3000
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: umami-config
                  key: POSTGRES_PASSWORD
            - name: DATABASE_URL
              value: "postgresql://umami:$(POSTGRES_PASSWORD)@umami-db:5432/umami"
            - name: APP_SECRET
              valueFrom:
                secretKeyRef:
                  name: umami-config
                  key: APP_SECRET
            # Disable Umami's own telemetry
            - name: DISABLE_TELEMETRY
              value: "1"
            - name: TZ
              value: "Europe/Budapest"
          resources:
            requests:
              memory: "128Mi"
              cpu: "50m"
            limits:
              memory: "512Mi"
              cpu: "500m"
          livenessProbe:
            httpGet:
              path: /api/heartbeat
              port: 3000
            initialDelaySeconds: 30
            periodSeconds: 30
          readinessProbe:
            httpGet:
              path: /api/heartbeat
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
  name: umami
  namespace: felhom-system
spec:
  selector:
    app: umami
  ports:
    - port: 80
      targetPort: 3000
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: umami
  namespace: felhom-system
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx-internal
  tls:
    - hosts:
        - stats.felhom.eu
      secretName: umami-tls
  rules:
    - host: stats.felhom.eu
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: umami
                port:
                  number: 80

# =============================================================================
# TRACKING SCRIPT - Add to your HTML pages
# =============================================================================
#
# After deploying and creating your website in Umami, add this to every page's
# <head> section (replace WEBSITE_ID with the ID from Umami dashboard):
#
#   <script defer src="https://stats.felhom.eu/script.js" data-website-id="YOUR-WEBSITE-ID"></script>
#
# The script is <2KB, async/deferred, cookie-free, and GDPR compliant.
# No cookie consent banner needed!
#
# TIP: Since your HTML files are managed via FileBrowser, you can add the
# script tag to all pages at once. Add it right before </head> in:
#   - index.html
#   - alkalmazasok.html
#   - technologiak.html
#   - gyik.html
#   - kapcsolat.html
#   - biztonsagimentes.html (if exists)
#   - Any other pages