---
# ConfigMap with PostgreSQL initialization SQL
apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-init-sql-tls
  namespace: netbox-enterprise
data:
  init.sql: |
    -- netbox Database
    \c netbox;
    ALTER DATABASE netbox OWNER TO netbox;
    GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox;
    GRANT ALL PRIVILEGES ON SCHEMA public TO netbox;
    GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO netbox;
    GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO netbox;
    GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO netbox;
    -- Grant default privileges for future objects (PostgreSQL 15+ compatibility)
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO netbox;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO netbox;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO netbox;

    -- diode Database
    \c diode;
    ALTER DATABASE diode OWNER TO diode;
    GRANT ALL PRIVILEGES ON DATABASE diode TO diode;
    GRANT ALL PRIVILEGES ON SCHEMA public TO diode;
    GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO diode;
    GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO diode;
    GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO diode;
    -- Grant default privileges for future objects (PostgreSQL 15+ compatibility)
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO diode;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO diode;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO diode;

    -- hydra Database
    \c hydra;
    ALTER DATABASE hydra OWNER TO hydra;
    GRANT ALL PRIVILEGES ON DATABASE hydra TO hydra;
    GRANT ALL PRIVILEGES ON SCHEMA public TO hydra;
    GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO hydra;
    GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO hydra;
    GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO hydra;
    -- Grant default privileges for future objects (PostgreSQL 15+ compatibility)
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO hydra;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO hydra;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO hydra;

---
# PostgresCluster with TLS enabled (certificates auto-generated by PGO)
#
# The CrunchyData Postgres Operator (PGO) automatically generates TLS certificates
# and stores them in secrets following the pattern:
#   - {cluster-name}-cluster-cert        (CA, server cert, server key)
#   - {cluster-name}-replication-cert    (CA, replication client cert, client key)
#
# These certificates are automatically mounted into PostgreSQL pods and used
# for encrypted connections.
apiVersion: postgres-operator.crunchydata.com/v1beta1
kind: PostgresCluster
metadata:
  name: netbox-external-db-tls-postgres
  namespace: netbox-enterprise
spec:
  postgresVersion: 18
  image: registry.developers.crunchydata.com/crunchydata/crunchy-postgres:ubi9-18.1-2550
  port: 5432

  # Database initialization
  databaseInitSQL:
    name: postgres-init-sql-tls
    key: init.sql

  # User configuration
  users:
    - name: postgres
    - name: netbox
      databases:
        - netbox
      options: SUPERUSER
    - name: diode
      databases:
        - diode
      options: SUPERUSER
    - name: hydra
      databases:
        - hydra
      options: SUPERUSER

  # Instance configuration
  instances:
    - name: instance1
      replicas: 1
      dataVolumeClaimSpec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 4Gi

  # Patroni configuration with TLS enabled
  # TLS certificates are auto-generated by PGO and mounted at /opt/crunchy/conf/
  patroni:
    dynamicConfiguration:
      postgresql:
        pg_hba:
          - host all all all scram-sha-256
        # Enable SSL/TLS
        ssl: "on"
        ssl_ca_file: /opt/crunchy/conf/ca.crt
        ssl_cert_file: /opt/crunchy/conf/server.crt
        ssl_key_file: /opt/crunchy/conf/server.key
    leaderLeaseDurationSeconds: 30
    port: 8008
    syncPeriodSeconds: 10

  # Backup configuration
  backups:
    pgbackrest:
      image: registry.developers.crunchydata.com/crunchydata/crunchy-pgbackrest:ubi9-2.56.0-2550
      repos:
        - name: repo1
          volume:
            volumeClaimSpec:
              accessModes:
                - ReadWriteOnce
              resources:
                requests:
                  storage: 1Gi

---
# NetBoxEnterprise using external PostgreSQL with TLS certificate verification
#
# This example demonstrates full TLS certificate verification using:
# - The CA certificate from the PGO-generated secret
# - verify-full SSL mode to verify server hostname matches certificate
#
# The PostgresCluster above automatically generates certificates stored in:
#   - netbox-external-db-tls-postgres-cluster-cert (contains ca.crt, tls.crt, tls.key)
#
# TLS configuration is defined once in postgresqlProfiles.netbox and referenced
# by all components (NetBox, Diode, Hydra) via postgresqlProfile.
#
apiVersion: netboxlabs.com/v1alpha1
kind: NetBoxEnterprise
metadata:
  name: netbox-external-db-tls
  namespace: netbox-enterprise
spec:
  # imagePullSecrets:
  #   - netbox-enterprise-registry
  #   - enterprise-pull-secret
  #   - kotsadm-replicated-registry
  imagePullPolicy: IfNotPresent
  tlsKeychain:
    caCertificateSecrets:
      - name: my-self-signed-ca
        # optional, defaults to the same as the `name` field
        secret: self-signed-ca-secret
        # optional, defaults to `ca.crt`
        key: ca.crt
      - name: another-ca-secret
      # generated by PGO for the PostgreSQL cluster
      - name: pgo
        secret: netbox-external-db-tls-postgres-cluster-cert
    clientCertificateSecrets:
      - name: my-client-cert
        secret: my-client-cert-secret
        # optional, defaults to `tls.crt`
        certKey: tls.crt
        # optional, defaults to `tls.key`
        privateKey: tls.key
      - name: some-cert-secret

  # Shared PostgreSQL connection profile — referenced by ALL components below
  # (NetBox, Diode, Hydra). Avoids repeating host, port, and TLS config.
  postgresqlProfiles:
    netbox:
      host: netbox-external-db-tls-postgres-primary.netbox-enterprise.svc
      port: 5432
      tlsConfig:
        # SSL mode for PostgreSQL connection - use verify-full for certificate verification
        sslmode: verify-full
        insecureSkipVerify: false
        # Reference CA certificates from keychain by name (for PGSSLROOTCERT)
        keychainCaCertificates: ['pgo']
        # Reference client certificate from keychain (for PGSSLCERT and PGSSLKEY)
        keychainClientCertificate: my-client-cert

  netbox:
    replicas: 1
    image:
      pullPolicy: IfNotPresent
    worker:
      replicas: 1
  diode:
    enabled: true
    config:
      reconciler:
        # Reference the shared profile for host, port, and TLS; supply only the
        # Diode-specific password.
        # Note: If postgres is omitted entirely, falls back to PGO secret:
        #       {cluster-name}-postgres-pguser-diode
        postgres:
          postgresqlProfile: netbox
          password:
            name: netbox-external-db-tls-postgres-pguser-diode
            key: password
      # Note: Ingester only needs Redis, no PostgreSQL configuration required
    hydra:
      # Reference the shared profile for host, port, and TLS.
      postgresqlProfile: netbox
      # When using external PostgreSQL, Hydra secrets must be manually configured.
      # The operator will not auto-generate these when postgresql.external: true.
      secrets:
        # System secret for Hydra encryption (auto-generated by operator during initial creation)
        system:
          name: netbox-external-db-tls-diode-hydra-secret
          key: secretsSystem
        # Cookie secret for Hydra session management (auto-generated by operator during initial creation)
        cookie:
          name: netbox-external-db-tls-diode-hydra-secret
          key: secretsCookie
        # Database DSN from PGO-generated user secret
        dsn:
          name: netbox-external-db-tls-postgres-pguser-hydra
          key: uri
  postgresql:
    # Mark as external so operator doesn't create its own PostgresCluster
    external: true
    # Reference the shared profile for host, port, and TLS.
    # All external PostgreSQL config flows through postgresqlProfiles.
    postgresqlProfile: netbox

  redis:
    external: false

# ---
# Alternative: Using keychain-based TLS for AWS RDS, GCP Cloud SQL, etc.
#
# For connecting to external databases, create a secret with the CA certificate first:
#
#   kubectl create secret generic external-db-ca-cert \
#     --from-file=ca.crt=/path/to/rds-ca-bundle.pem
#
# apiVersion: netboxlabs.com/v1alpha1
# kind: NetBoxEnterprise
# metadata:
#   name: netbox-cloud-db
# spec:
#   tlsKeychain:
#     caCertificateSecrets:
#       - name: rds-ca
#         secret: external-db-ca-cert
#         key: ca.crt
#     clientCertificateSecrets:
#       - name: rds-client
#         secret: rds-client-cert
#   # Shared profile for all components
#   postgresqlProfiles:
#     netbox:
#       host: "mydb.123456789.us-east-1.rds.amazonaws.com"
#       port: 5432
#       tlsConfig:
#         sslmode: verify-full
#         keychainCaCertificates: ['rds-ca']
#         keychainClientCertificate: rds-client
#   postgresql:
#     external: true
#     postgresqlProfile: netbox

# ---
# Alternative: Diode with its own external database (different server from NetBox)
#
# When Diode connects to a different database server than NetBox, create a
# separate profile for Diode with its own host/port/TLS.
#
# apiVersion: netboxlabs.com/v1alpha1
# kind: NetBoxEnterprise
# metadata:
#   name: netbox-diode-separate-db
# spec:
#   tlsKeychain:
#     caCertificateSecrets:
#       - name: netbox-db-ca
#         secret: netbox-db-ca-cert
#       - name: diode-db-ca
#         secret: diode-db-ca-cert
#     clientCertificateSecrets:
#       - name: diode-client
#         secret: diode-client-cert
#   postgresqlProfiles:
#     netbox:
#       host: "netbox-db.example.com"
#       port: 5432
#       tlsConfig:
#         sslmode: verify-full
#         keychainCaCertificates: ['netbox-db-ca']
#     diode:
#       host: "diode-db.123456789.us-east-1.rds.amazonaws.com"
#       port: 5432
#       tlsConfig:
#         sslmode: verify-full
#         insecureSkipVerify: false
#         keychainCaCertificates: ['diode-db-ca']
#         keychainClientCertificate: diode-client
#   postgresql:
#     external: true
#     postgresqlProfile: netbox
#   diode:
#     enabled: true
#     config:
#       reconciler:
#         databaseName: diode
#         databaseUser: diode
#         postgres:
#           postgresqlProfile: diode
#           password:
#             name: diode-rds-credentials
#             key: password
