# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "hlf-ca.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "hlf-ca.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "hlf-ca.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{- /*
Credit: @technosophos
https://github.com/technosophos/common-chart/
labels.standard prints the standard Helm labels.
The standard labels are frequently used in metadata.
*/ -}}
{{- define "labels.standard" -}}
app: {{ include "hlf-ca.name" . }}
heritage: {{ .Release.Service | quote }}
release: {{ .Release.Name | quote }}
chart: {{ include "hlf-ca.chart" . }}
{{- end -}}

{{/*
Generate postgres chart name
*/}}
{{- define "postgresql.fullname" -}}
{{- printf "%s-%s" .Release.Name "postgresql" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Generate mysql chart name
*/}}
{{- define "mysql.fullname" -}}
{{- printf "%s-%s" .Release.Name "mysql" | trunc 63 | trimSuffix "-" -}}
{{- end -}}
 # configmap--ca.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "hlf-ca.fullname" . }}--ca
  labels:
{{ include "labels.standard" . | indent 4 }}
data:
  GODEBUG: "netdns=go"
  FABRIC_CA_HOME: /var/hyperledger/fabric-ca
  FABRIC_CA_SERVER_CA_NAME: {{ .Values.caName | quote }}
  SERVICE_DNS: 0.0.0.0  # Point to itself
 # configmap--config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "hlf-ca.fullname" . }}--config
  labels:
{{ include "labels.standard" . | indent 4 }}
data:
  ca.yaml: |
    #############################################################################
    #   This is a configuration file for the fabric-ca-server command.
    #############################################################################
    # Version of config file
    version: {{ .Values.config.hlfToolsVersion }}
    # Server's listening port
    port: 7054
    # Enables debug logging
    debug: {{ .Values.config.debug }}
    # Size limit of an acceptable CRL in bytes (default: 512000)
    crlsizelimit: 512000
    #############################################################################
    #  TLS section
    #############################################################################
    tls:
      # Enable TLS (handled by the Ingress)
      enabled: false
      # TLS for the server's listening port
      certfile: /var/hyperledger/tls/secret/tls.crt
      keyfile: /var/hyperledger/tls/secret/tls.key
      clientauth:
        # Supported types: NoClientCert, RequestClientCert, RequireAnyClientCert, VerifyClientCertIfGiven and RequireAndVerifyClientCert.
        type: noclientcert
        # List of root certificate authorities used when verifying client certificates
        certfiles:
    #############################################################################
    #  The CA section contains information related to the Certificate Authority
    #  including the name of the CA, which should be unique for all members
    #  of a blockchain network.  It also includes the key and certificate files
    #  used when issuing enrollment certificates (ECerts) and transaction
    #  certificates (TCerts).
    #  The chainfile (if it exists) contains the certificate chain which
    #  should be trusted for this CA, where the 1st in the chain is always the
    #  root CA certificate.
    #############################################################################
    ca:
      # Name of this CA
      name:
      # Key file (is only used to import a private key into BCCSP)
      keyfile:
      # Certificate file (default: ca-cert.pem)
      certfile: /var/hyperledger/fabric-ca/msp/certs/{{ include "hlf-ca.fullname" . }}-cert.pem
      # Chain file
      chainfile:
    #############################################################################
    #  The gencrl REST endpoint is used to generate a CRL that contains revoked
    #  certificates. This section contains configuration options that are used
    #  during gencrl request processing.
    #############################################################################
    crl:
      # Specifies expiration for the generated CRL. The number of hours
      # specified by this property is added to the UTC time, the resulting time
      # is used to set the 'Next Update' date of the CRL.
      expiry: 24h
    #############################################################################
    #  The registry section controls how the fabric-ca-server does two things:
    #  1) authenticates enrollment requests which contain a username and password
    #     (also known as an enrollment ID and secret).
    #  2) once authenticated, retrieves the identity's attribute names and
    #     values which the fabric-ca-server optionally puts into TCerts
    #     which it issues for transacting on the Hyperledger Fabric blockchain.
    #     These attributes are useful for making access control decisions in
    #     chaincode.
    #  There are two main configuration options:
    #  1) The fabric-ca-server is the registry.
    #     This is true if "ldap.enabled" in the ldap section below is false.
    #  2) An LDAP server is the registry, in which case the fabric-ca-server
    #     calls the LDAP server to perform these tasks.
    #     This is true if "ldap.enabled" in the ldap section below is true,
    #     which means this "registry" section is ignored.
    #############################################################################
    registry:
      # Maximum number of times a password/secret can be reused for enrollment
      # (default: -1, which means there is no limit)
      maxenrollments: -1
      # Contains identity information which is used when LDAP is disabled
      identities:
         - name: <<<ADMIN>>>
           pass: <<<ADMINPW>>>
           type: client
           affiliation: ""
           attrs:
              hf.Registrar.Roles: "peer,orderer,client,user"
              hf.Registrar.DelegateRoles: "peer,orderer,client,user"
              hf.Revoker: true
              hf.IntermediateCA: true
              hf.GenCRL: true
              hf.Registrar.Attributes: "*"
              hf.AffiliationMgr: true
    #############################################################################
    #  Database section
    #  Supported types are: "sqlite3", "postgres", and "mysql".
    #  The datasource value depends on the type.
    #  If the type is "sqlite3", the datasource value is a file name to use
    #  as the database store.  Since "sqlite3" is an embedded database, it
    #  may not be used if you want to run the fabric-ca-server in a cluster.
    #  To run the fabric-ca-server in a cluster, you must choose "postgres"
    #  or "mysql".
    #############################################################################
    db:
      type: <<<DB_TYPE>>>
      datasource: <<<DB_DATASOURCE>>>
      tls:
          enabled: false
          certfiles:
          client:
            certfile:
            keyfile:
    #############################################################################
    #  LDAP section
    #  If LDAP is enabled, the fabric-ca-server calls LDAP to:
    #  1) authenticate enrollment ID and secret (i.e. username and password)
    #     for enrollment requests;
    #  2) To retrieve identity attributes
    #############################################################################
    ldap:
       # Enables or disables the LDAP client (default: false)
       # If this is set to true, the "registry" section is ignored.
       enabled: false
       # The URL of the LDAP server
       url: ldap://<adminDN>:<adminPassword>@<host>:<port>/<base>
       # TLS configuration for the client connection to the LDAP server
       tls:
          certfiles:
          client:
             certfile:
             keyfile:
       # Attribute related configuration for mapping from LDAP entries to Fabric CA attributes
       attribute:
          # 'names' is an array of strings containing the LDAP attribute names which are
          # requested from the LDAP server for an LDAP identity's entry
          names: ['uid','member']
          # The 'converters' section is used to convert an LDAP entry to the value of
          # a fabric CA attribute.
          # For example, the following converts an LDAP 'uid' attribute
          # whose value begins with 'revoker' to a fabric CA attribute
          # named "hf.Revoker" with a value of "true" (because the boolean expression
          # evaluates to true).
          #    converters:
          #       - name: hf.Revoker
          #         value: attr("uid") =~ "revoker*"
          converters:
             - name:
               value:
          # The 'maps' section contains named maps which may be referenced by the 'map'
          # function in the 'converters' section to map LDAP responses to arbitrary values.
          # For example, assume a user has an LDAP attribute named 'member' which has multiple
          # values which are each a distinguished name (i.e. a DN). For simplicity, assume the
          # values of the 'member' attribute are 'dn1', 'dn2', and 'dn3'.
          # Further assume the following configuration.
          #    converters:
          #       - name: hf.Registrar.Roles
          #         value: map(attr("member"),"groups")
          #    maps:
          #       groups:
          #          - name: dn1
          #            value: peer
          #          - name: dn2
          #            value: client
          # The value of the user's 'hf.Registrar.Roles' attribute is then computed to be
          # "peer,client,dn3".  This is because the value of 'attr("member")' is
          # "dn1,dn2,dn3", and the call to 'map' with a 2nd argument of
          # "group" replaces "dn1" with "peer" and "dn2" with "client".
          maps:
             groups:
                - name:
                  value:
    #############################################################################
    # Affiliations section, specified as hierarchical maps.
    # Note: Affiliations are case sensitive except for the non-leaf affiliations.
    #############################################################################
    affiliations:
    {{- toYaml .Values.config.affiliations | nindent 6 }}
    #############################################################################
    #  Signing section
    #
    #  The "default" subsection is used to sign enrollment certificates;
    #  the default expiration ("expiry" field) is "8760h", which is 1 year in hours.
    #
    #  The "ca" profile subsection is used to sign intermediate CA certificates;
    #  the default expiration ("expiry" field) is "43800h" which is 5 years in hours.
    #  Note that "isca" is true, meaning that it issues a CA certificate.
    #  A maxpathlen of 0 means that the intermediate CA cannot issue other
    #  intermediate CA certificates, though it can still issue end entity certificates.
    #  (See RFC 5280, section 4.2.1.9)
    #
    #  The "tls" profile subsection is used to sign TLS certificate requests;
    #  the default expiration ("expiry" field) is "8760h", which is 1 year in hours.
    #############################################################################
    signing:
        default:
          usage:
            - digital signature
          expiry: 8760h
        profiles:
          ca:
             usage:
               - cert sign
               - crl sign
             expiry: 43800h
             caconstraint:
               isca: true
               maxpathlen: 0
          tls:
             usage:
                - signing
                - key encipherment
                - server auth
                - client auth
                - key agreement
             expiry: 8760h
    ###########################################################################
    #  Certificate Signing Request (CSR) section.
    #  This controls the creation of the root CA certificate.
    #  The expiration for the root CA certificate is configured with the
    #  "ca.expiry" field below, whose default value is "131400h" which is
    #  15 years in hours.
    #  The pathlength field is used to limit CA certificate hierarchy as described
    #  in section 4.2.1.9 of RFC 5280.
    #  Examples:
    #  1) No pathlength value means no limit is requested.
    #  2) pathlength == 1 means a limit of 1 is requested which is the default for
    #     a root CA.  This means the root CA can issue intermediate CA certificates,
    #     but these intermediate CAs may not in turn issue other CA certificates
    #     though they can still issue end entity certificates.
    #  3) pathlength == 0 means a limit of 0 is requested;
    #     this is the default for an intermediate CA, which means it can not issue
    #     CA certificates though it can still issue end entity certificates.
    ###########################################################################
    csr:
       {{- if .Values.config.intermediate }}
       cn:
       {{- else}}
       cn: {{ .Values.caName | quote }}
       {{- end}}
       names:
          - C: {{ .Values.config.csr.names.c | quote }}
            ST: {{ .Values.config.csr.names.st | quote }}
            L: {{ .Values.config.csr.names.l | quote }}
            O: {{ .Values.config.csr.names.o | quote }}
            OU: {{ .Values.config.csr.names.ou | quote }}
       hosts:
         - localhost
         # K8S Service
         - {{ include "hlf-ca.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local
         {{- if .Values.ingress.enabled }}
         # Ingresses
         {{- range .Values.ingress.hosts }}
         - {{ . }}
         {{- end }}
         {{- end }}
       ca:
          expiry: 131400h
          pathlength: {{ .Values.config.csr.ca.pathlength}}
    #############################################################################
    # BCCSP (BlockChain Crypto Service Provider) section is used to select which
    # crypto library implementation to use
    #############################################################################
    bccsp:
        default: SW
        sw:
            hash: SHA2
            security: 256
            filekeystore:
                # The directory used for the software file-based keystore
                keystore: msp/keystore
    #############################################################################
    # Multi CA section (unused in a K8S deployment)
    #############################################################################
    cacount:
    cafiles:
    #############################################################################
    # Intermediate CA section
    #
    # The relationship between servers and CAs is as follows:
    #   1) A single server process may contain or function as one or more CAs.
    #      This is configured by the "Multi CA section" above.
    #   2) Each CA is either a root CA or an intermediate CA.
    #   3) Each intermediate CA has a parent CA which is either a root CA or another intermediate CA.
    #
    # This section pertains to configuration of #2 and #3.
    # If the "intermediate.parentserver.url" property is set,
    # then this is an intermediate CA with the specified parent
    # CA.
    #
    # parentserver section
    #    url - The URL of the parent server
    #    caname - Name of the CA to enroll within the server
    #
    # enrollment section used to enroll intermediate CA with parent CA
    #    profile - Name of the signing profile to use in issuing the certificate
    #    label - Label to use in HSM operations
    #
    # tls section for secure socket connection
    #   certfiles - PEM-encoded list of trusted root certificate files
    #   client:
    #     certfile - PEM-encoded certificate file for when client authentication
    #     is enabled on server
    #     keyfile - PEM-encoded key file for when client authentication
    #     is enabled on server
    #############################################################################
    intermediate:
      parentserver:
        {{- if .Values.config.intermediate }}
        url: http://<<<PARENT_ADMIN>>>:<<<PARENT_ADMINPW>>>@{{ .Values.config.intermediate.parent.url }}:{{ .Values.config.intermediate.parent.port }}
        {{- else}}
        url:
        {{- end}}
        caname:
      enrollment:
        hosts:
        profile:
        label:
      tls:
        certfiles:
        client:
          certfile:
          keyfile:
    #############################################################################
    # Extra configuration options
    # .e.g to enable adding and removing affiliations or identities
    #############################################################################
    cfg:
      affiliations:
        allowremove: true
      identities:
        allowremove: true
 # configmap--db.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "hlf-ca.fullname" . }}--db
  labels:
{{ include "labels.standard" . | indent 4 }}
data:
  DB_SSL: {{ .Values.db.ssl | quote }}
  {{- if .Values.postgresql.enabled }}
  # PostgreSQL Database
  DB_TYPE: "postgres"
  DB_HOST: {{ template "postgresql.fullname" . }}
  DB_PORT: {{ .Values.postgresql.service.port | quote }}
  DB_USERNAME: {{ .Values.postgresql.postgresqlUsername | quote }}
  DB_DATABASE: {{ .Values.postgresql.postgresqlDatabase  | quote }}
  {{- end }}
  {{- if .Values.mysql.enabled }}
  # MySQL Database
  DB_TYPE: "mysql"
  DB_HOST: {{ template "mysql.fullname" . }}
  DB_PORT: "3306"
  DB_USERNAME: {{ .Values.mysql.mysqlUser | quote }}
  DB_DATABASE: {{ .Values.mysql.mysqlDatabase  | quote }}
  {{- end }}
  {{- if .Values.externalDatabase.type }}
  # External Database
  DB_TYPE: {{ .Values.externalDatabase.type | quote }}
  DB_HOST: {{ .Values.externalDatabase.host | quote }}
  {{- if eq .Values.externalDatabase.type "mysql" }}
  DB_PORT: {{ .Values.externalDatabase.port | default "3306" | quote }}
  {{- end }}
  {{- if eq .Values.externalDatabase.type "postgres" }}
  DB_PORT: {{ .Values.externalDatabase.port | default "5432" | quote }}
  {{- end }}
  DB_USERNAME: {{ .Values.externalDatabase.username | quote }}
  DB_DATABASE: {{ .Values.externalDatabase.database  | quote }}
  {{- end }} # deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "hlf-ca.fullname" . }}
  labels:
{{ include "labels.standard" . | indent 4 }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ include "hlf-ca.name" . }}
      release: {{ .Release.Name }}
  # Ensure we allow our pod to be unavailable, so we can upgrade
  strategy:
    rollingUpdate:
      maxUnavailable: 1
  template:
    metadata:
      labels:
{{ include "labels.standard" . | indent 8 }}
    spec:
      volumes:
        - name: data
        {{- if .Values.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ .Values.persistence.existingClaim | default (include "hlf-ca.fullname" .) }}
        {{- else }}
          emptyDir: {}
        {{- end }}
        {{- if (and .Values.config.mountTLS .Values.ingress.tls) }}
        - name: tls-secret
          secret:
            secretName: {{ (index .Values.ingress.tls 0).secretName }}
        {{- end }}
        - name: ca-config
          configMap:
            name: {{ include "hlf-ca.fullname" . }}--config    
      initContainers:
        - name: wait-for-db
          image: jwilder/dockerize
          imagePullPolicy: IfNotPresent 
          envFrom:
            - configMapRef:
                name: {{ include "hlf-ca.fullname" . }}--db
          command: 
            - sh
            - -c
            - |
              if [ -n "$DB_TYPE" ]; then
                dockerize -wait tcp://$DB_HOST:$DB_PORT -timeout 30s && echo "Database $DB_TYPE on $DB_HOST:$DB_PORT is ready"
              fi
      containers:
        - name: ca
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command:
            - sh
            - -c
            - |
              if [ -n "$DB_TYPE" ]; then
                while [ -z ${DB_PASSWORD+x} ];
                do
                  echo "\033[0;31mDB_PASSWORD environmental variable must contain a value \033[0m"
                  sleep 60
                done

                case "$DB_TYPE" in
                  postgres)
                    export DB_DATASOURCE="host=${DB_HOST} port=${DB_PORT} user=${DB_USERNAME} password=${DB_PASSWORD} dbname=${DB_DATABASE} sslmode=${DB_SSL}";;
                  mysql)
                    export DB_DATASOURCE="${DB_USERNAME}:${DB_PASSWORD}@tcp(${DB_HOST}:${DB_PORT})/${DB_DATABASE}?parseTime=true" ;;
                  *)
                    echo "\033[0;31m Database type '$DB_TYPE' not supported\033[0m"; exit 1;;
                esac
              fi

              mkdir -p $FABRIC_CA_HOME
              cp /var/hyperledger/ca_config/ca.yaml $FABRIC_CA_HOME/fabric-ca-server-config.yaml
              sed -i "s|<<<ADMIN>>>|${CA_ADMIN}|g" ${FABRIC_CA_HOME}/fabric-ca-server-config.yaml
              sed -i "s|<<<ADMINPW>>>|${CA_PASSWORD}|g" $FABRIC_CA_HOME/fabric-ca-server-config.yaml
              sed -i "s|<<<DB_TYPE>>>|${DB_TYPE:-"sqlite3"}|g" $FABRIC_CA_HOME/fabric-ca-server-config.yaml
              sed -i "s|<<<DB_DATASOURCE>>>|${DB_DATASOURCE:-"fabric-ca-server.db"}|g" $FABRIC_CA_HOME/fabric-ca-server-config.yaml

              {{- if .Values.config.intermediate }}
              echo ">\033[0;33m Adding Parent CA (typically a Root CA) values to $FABRIC_CA_HOME/fabric-ca-server-config.yaml\033[0m"
              sed -i "s|<<<PARENT_ADMIN>>>|${PARENT_CA_ADMIN}|g" $FABRIC_CA_HOME/fabric-ca-server-config.yaml
              sed -i "s|<<<PARENT_ADMINPW>>>|${PARENT_CA_PASSWORD}|g" $FABRIC_CA_HOME/fabric-ca-server-config.yaml
              {{- end}}

              echo ">\033[0;35m fabric-ca-server start \033[0m"
              fabric-ca-server start
          envFrom:
            - secretRef:
                name: {{ include "hlf-ca.fullname" . }}--ca
            - configMapRef:
                name: {{ include "hlf-ca.fullname" . }}--db
            - configMapRef:
                name: {{ include "hlf-ca.fullname" . }}--ca
          env:
            {{- if .Values.postgresql.enabled}}
            # PostgreSQL Database
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "postgresql.fullname" . }}
                  key: postgresql-password
            {{- end }}
            {{- if .Values.mysql.enabled }}
            # MySQL Database
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "mysql.fullname" . }}
                  key: mysql-password
            {{- end }}
            {{- if .Values.externalDatabase.type }}
            # External Database
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "hlf-ca.fullname" . }}--db
                  key: db-password
            {{- end }}            
            {{- if .Values.config.intermediate }}
            # Intermediate CA
            - name: PARENT_CA_ADMIN
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.config.intermediate.parent.chart }}--ca
                  key: CA_ADMIN
            - name: PARENT_CA_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.config.intermediate.parent.chart }}--ca
                  key: CA_PASSWORD
            {{- end}}
          ports:
            - name: ca-port
              containerPort: 7054
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /cainfo
              port: 7054
          readinessProbe:
            httpGet:
              path: /cainfo
              port: 7054             
          volumeMounts:
            - name: data
              mountPath: /var/hyperledger
            - name: ca-config
              readOnly: true
              mountPath: /var/hyperledger/ca_config
            {{- if (and .Values.config.mountTLS .Values.ingress.tls) }}
            - name: tls-secret
              readOnly: true
              mountPath: /var/hyperledger/tls/secret
            {{- end }}
          resources:
{{ toYaml .Values.resources | indent 12 }}
    {{- with .Values.nodeSelector }}
      nodeSelector:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
      affinity:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
    {{- end }}
 # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "hlf-ca.fullname" . -}}
{{- $ingressPath := .Values.ingress.path -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ $fullName }}
  labels:
{{ include "labels.standard" . | indent 4 }}
{{- with .Values.ingress.annotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.tls }}
  tls:
  {{- range .Values.ingress.tls }}
    - hosts:
      {{- range .hosts }}
        - {{ . }}
      {{- end }}
      secretName: {{ .secretName }}
  {{- end }}
{{- end }}
  rules:
  {{- range .Values.ingress.hosts }}
    - host: {{ . }}
      http:
        paths:
          - path: {{ $ingressPath }}
            backend:
              serviceName: {{ $fullName }}
              servicePort: http
  {{- end }}
{{- end }}
 # pvc.yaml
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: {{ include "hlf-ca.fullname" . }}
  labels:
{{ include "labels.standard" . | indent 4 }}
{{- if .Values.persistence.annotations }}
  annotations:
{{ toYaml .Values.persistence.annotations | indent 4 }}
{{- end }}
spec:
  accessModes:
    - {{ .Values.persistence.accessMode | quote }}
  resources:
    requests:
      storage: {{ .Values.persistence.size | quote }}
  {{- if .Values.persistence.storageClass }}
  {{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
  {{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
  {{- end }}
  {{- end }}
{{- end }}
 # secret--ca.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "hlf-ca.fullname" . }}--ca
  labels:
{{ include "labels.standard" . | indent 4 }}
type: Opaque
data:
  CA_ADMIN: {{ .Values.adminUsername | b64enc | quote }}
  {{ if .Values.adminPassword }}
  CA_PASSWORD:  {{ .Values.adminPassword | b64enc | quote }}
  {{ else }}
  CA_PASSWORD: {{ randAlphaNum 24 | b64enc | quote }}
  {{ end }}
 # secret--db.yaml
{{- if .Values.externalDatabase.type }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "hlf-ca.fullname" . }}--db
  labels:
{{ include "labels.standard" . | indent 4 }}
type: Opaque
data:
  db-password: {{ .Values.externalDatabase.password | b64enc | quote }}
{{- end }} # service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ include "hlf-ca.fullname" . }}
  labels:
{{ include "labels.standard" . | indent 4 }}
spec:
  type: {{ .Values.service.type | quote }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: 7054
      protocol: TCP
      name: http
  selector:
    app: {{ include "hlf-ca.name" . }}
    release: {{ .Release.Name }}

## Default values for hlf-ca.
## This is a YAML-formatted file.
## Declare variables to be passed into your templates.

image:
  repository: hyperledger/fabric-ca
  tag: 1.4.3
  pullPolicy: IfNotPresent

service:
  ## Cluster IP or LoadBalancer
  type: ClusterIP
  port: 7054

ingress:
  enabled: false
  annotations: {}
    # kubernetes.io/ingress.class: nginx
    # certmanager.k8s.io/cluster-issuer: "letsencrypt-staging"
  path: /
  hosts:
    - hlf-ca.local
  tls: []
  #  - secretName: hlf-ca-tls
  #    hosts:
  #      - hlf-ca.local

persistence:
  enabled: true
  annotations: {}
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  storageClass: ""
  accessMode: ReadWriteOnce
  size: 1Gi
  # existingClaim: ""

##################################
## Further configuration options #
##################################
## CA Admin Username
adminUsername: admin
## CA Admin password (set to 24 random characters by default)
# adminPassword:
## Name of CA, stored in FABRIC_CA_SERVER_CA_NAME (and the configMap "--config", if deploying a Root CA)
caName: org1-ca

##
## Fabric CA Database
## By default an sqlite3 in-memory database is used
## To install a 'postgresql' or 'mysql' database, enable and configure the configuration below
##################################
##
db:
  # SSL authentication
  # Supported values are: "disable", "require", "verify-ca" and "verify-full".
  # https://github.com/hyperledger/fabric-ca/blob/master/docs/source/users-guide.rst
  ssl: disable

##
## PostgreSQL chart configuration
##
## https://github.com/helm/charts/tree/master/stable/postgresql
##
postgresql:
  ## Whether to deploy a postgres server to satisfy the Fabric CA database requirements.
  # To use an external database set this to false and configure the externalDatabase parameters, specifying the type to 'postgres'
  enabled: false
  image:
    registry: docker.io
    repository: "bitnami/postgresql"
    tag: "10.10.0"
  postgresqlDatabase: fabric_ca
  postgresqlUsername: fabric_ca

##
## MySQL chart configuration
##
## https://github.com/helm/charts/tree/master/stable/mysql
##
mysql:
  ## Whether to deploy a mysql server to satisfy the Fabric CA database requirements.
  # To use an external database set this to false and configure the externalDatabase parameters, specifying the type to 'mysql'
  enabled: false
  image: "mysql"
  imageTag: "5.7.27"
  mysqlDatabase: fabric_ca
  mysqlUser: fabric_ca
  # Custom mysql configuration to remove SQL Mode NO_ZERO_DATE because the Fabric CA schema defines TIMESTAMP to 0 by default
  # https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
  configurationFiles:
    mysql.cnf: |-
      [mysqld]
      sql-mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

##
## External Database configuration (MySQL or PostgresSQL installed on/off Kubernetes)
##
externalDatabase:
  # Either postgres or mysql
  type:
  host: ""
  port: ""
  database: ""
  username: ""
  password: ""

## Settings used in configMap "--config"
config:
  hlfToolsVersion: 1.4.3
  ## Mount the TLS certificate & key to disk?
  mountTLS: false
  ## Enable debug logging in ca Server configuration file
  debug: true
  ## CSR pathlength in ca Server configuration file
  csr:
    ca:
      pathlength: 1
    names:
      c: US
      st: "North Carolina"
      l:
      o: Hyperledger
      ou: Fabric
  ## "intermediate" is only specified for Intermediate CA's
  # intermediate:
  #   parent:
  #     chart: parent-ca
  #     url: parent-ca.example.com
  #     port: 7054
  ## Affiliations used in ca Server configuration file
  affiliations: {}
    # org1: []

resources: {}
  ## We usually recommend not to specify default resources and to leave this as a conscious
  ## choice for the user. This also increases chances charts run on environments with little
  ## resources, such as Minikube. If you do want to specify resources, uncomment the following
  ## lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  # requests:
  #   cpu: 100m
  #   memory: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}
  ## Suggested antiAffinity, as each CA should be on a separate Node for resilience
  # podAntiAffinity:
  #   requiredDuringSchedulingIgnoredDuringExecution:
  #     - topologyKey: "kubernetes.io/hostname"
  #       labelSelector:
  #         matchLabels:
  #           app: hlf-ca
