apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "hlf-peer.fullname" . }}
  labels:
{{ include "labels.standard" . | indent 4 }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ include "hlf-peer.name" . }}
      release: {{ .Release.Name }}
  template:
    metadata:
      labels:
{{ include "labels.standard" . | indent 8 }}
    spec:
      volumes:
        - name: data
        {{- if .Values.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ .Values.persistence.existingClaim | default (include "hlf-peer.fullname" .) }}
        {{- else }}
          emptyDir: {}
        {{- end }}
        - name: dockersocket
          hostPath:
            path: /var/run/docker.sock
        {{- if .Values.secrets.channel }}
        - name: channel
          secret:
            secretName: {{ .Values.secrets.channel }}
        {{- end }}
        {{- if .Values.secrets.adminCert }}
        - name: admin-cert
          secret:
            secretName: {{ .Values.secrets.adminCert }}
        {{- end }}
        {{- if .Values.secrets.adminKey }}
        - name: admin-key
          secret:
            secretName: {{ .Values.secrets.adminKey }}
        {{- end }}
      containers:
        - name: peer
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: request
              containerPort: 7051
              protocol: TCP
            - name: event
              containerPort: 7053
              protocol: TCP
          # TODO: Add liveness and readiness probes
          command:
            - sh
            - -c
            - |
              # To avoid having separate secrets for CouchDB and HLF
              export CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=$COUCHDB_USER
              export CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=$COUCHDB_PASSWORD

              while [ ! -d /hl_config/admin/admincerts ] || [ -z "$(ls -A /hl_config/admin/admincerts)" ];
              do
                echo "\033[0;31m /hl_config/admin/admincerts must contain Peer admin certificates files \033[0m"
                sleep 60
              done
            
              # Download Fabric CA-client if it does not exist
              if [ ! -f /bin/fabric-ca-client ]
              then
                if [ ! -f /var/hyperledger/fabric-ca-${HLF_TOOLS_BUILD}.tar.gz ]
                then
                  # Curl is needed to download Fabric CA-client
                  apt update
                  apt install curl -y

                  echo "Downloading Fabric CA-client"
                  curl -f -s -C - https://nexus.hyperledger.org/content/repositories/releases/org/hyperledger/fabric-ca/hyperledger-fabric-ca/${HLF_TOOLS_BUILD}/hyperledger-fabric-ca-${HLF_TOOLS_BUILD}.tar.gz > /var/hyperledger/fabric-ca-${HLF_TOOLS_BUILD}.tar.gz
                fi
                echo "Unzipping Fabric CA-client"
                tar xzf /var/hyperledger/fabric-ca-${HLF_TOOLS_BUILD}.tar.gz -C /
              fi

              while [ ! -f ${CORE_PEER_MSPCONFIGPATH}/signcerts/cert.pem ];
              do
                echo ">\033[0;35m fabric-ca-client enroll -d -u http://${CA_USERNAME}:${CA_PASSWORD}@${CA_ADDRESS} -M ${CORE_PEER_MSPCONFIGPATH} \033[0m"
                fabric-ca-client enroll -d -u http://${CA_USERNAME}:${CA_PASSWORD}@${CA_ADDRESS} -M ${CORE_PEER_MSPCONFIGPATH}

                if [ ! -f ${CORE_PEER_MSPCONFIGPATH}/signcerts/cert.pem ]
                then
                  echo ">\033[0;31m Unable to enroll Peer, make sure you have registered them first \(sleeping 180 seconds and re-trying\) \033[0m"
                  sleep 180
                fi
              done

              echo ">\033[0;32m Copy admincerts to ${CORE_PEER_MSPCONFIGPATH}/admincerts \033[0m"
              mkdir -p ${CORE_PEER_MSPCONFIGPATH}/admincerts
              cp -L /hl_config/admin/signcerts/* ${CORE_PEER_MSPCONFIGPATH}/admincerts

              echo ">\033[0;32m Setup admin certificates in ${ADMIN_MSP_PATH} \033[0m"
              mkdir -p ${ADMIN_MSP_PATH} ${ADMIN_MSP_PATH}/cacerts ${ADMIN_MSP_PATH}/intermediatecerts
              cp -L -r /hl_config/admin/* ${ADMIN_MSP_PATH}
              cp ${CORE_PEER_MSPCONFIGPATH}/cacerts/* ${ADMIN_MSP_PATH}/cacerts
              cp ${CORE_PEER_MSPCONFIGPATH}/intermediatecerts/* ${ADMIN_MSP_PATH}/intermediatecerts

              # Create TLS certificate for Peer
              if [ ! -f ${CORE_PEER_TLS_PRIVATEKEY} ]
              then
                echo ">\033[0;35m fabric-ca-client enroll -d --enrollment.profile tls -u http://${CA_USERNAME}:${CA_PASSWORD}@http://${CA_ADDRESS} -M /tmp/tls --csr.hosts {{ include "hlf-peer.fullname" . }} \033[0m"
                fabric-ca-client enroll -d --enrollment.profile tls -u http://${CA_USERNAME}:${CA_PASSWORD}@${CA_ADDRESS} -M /tmp/tls --csr.hosts {{ include "hlf-peer.fullname" . }}

                mkdir -p $(dirname $CORE_PEER_TLS_PRIVATEKEY)
                cp /tmp/tls/keystore/* $CORE_PEER_TLS_PRIVATEKEY
                mkdir -p $(dirname $CORE_PEER_TLS_CERTIFICATE)
                cp /tmp/tls/signcerts/* $CORE_PEER_TLS_CERTIFICATE
                #rm -rf /tmp/tls
              fi

              if [ ! -d ${FABRIC_CFG_PATH} ]
              then
                mkdir -p ${FABRIC_CFG_PATH}
                cp -r /etc/hyperledger/fabric/core.yaml ${FABRIC_CFG_PATH}
                ls ${FABRIC_CFG_PATH}
              fi

              echo ">\033[0;35m peer node start \033[0m"
              peer node start
          envFrom:
            - secretRef:
                name: {{ include "hlf-peer.fullname" . }}
            {{- if eq .Values.peer.databaseType "CouchDB" }}
            - secretRef:
                name: {{ .Values.peer.couchdbInstance }}-hlf-couchdb
            {{- end }}
            - configMapRef:
                name: {{ include "hlf-peer.fullname" . }}--peer
          volumeMounts:
            - mountPath: /var/hyperledger
              name: data
            - mountPath: /host/var/run/docker.sock
              name: dockersocket
            {{- if .Values.secrets.channel }}
            - mountPath: /hl_config/channel
              name: channel
            {{- end }}
            {{- if .Values.secrets.adminCert }}
            - mountPath: /hl_config/admin/admincerts
              name: admin-cert
            - mountPath: /hl_config/admin/signcerts
              name: admin-cert
            {{- end }}
            {{- if .Values.secrets.adminKey }}
            - mountPath: /hl_config/admin/keystore
              name: admin-key
            {{- end }}
          resources:
{{ toYaml .Values.resources | indent 12 }}
    {{- with .Values.nodeSelector }}
      nodeSelector:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
      affinity:
        ## This affinity is required to ensure reasonable ledger access speeds
        {{- if eq $.Values.peer.databaseType "CouchDB" }}
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: release
                operator: In
                values:
                - {{ $.Values.peer.couchdbInstance }}
            topologyKey: "kubernetes.io/hostname"
        {{- end }}
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
    {{- end }}
