---

#
# Check if the metering root CA secret already exists and instead needs to be copied into a temp directory
# This temp directory would contain all the necessary TLS data (shared with Presto, Hive, reporting-operator)
#
- name: Check for the existence of the Metering Root CA secret
  block:
  - name: Check if Root CA secret already exists
    k8s_facts:
      api_version: v1
      kind: Secret
      name: "{{ meteringconfig_spec.tls.secretName }}"
      namespace: "{{ meta.namespace }}"
    no_log: true
    register: root_ca_secret_buf

  # note: other resources (presto, hive, reporting-operator) depend on these variables
  - name: Use pre-existing CA secret cert/key when secret already exists
    block:
    - set_fact:
        _meteringconfig_tls_root_ca_certificate: "{{ root_ca_secret_buf.resources[0].data['ca.crt'] | b64decode }}"
        _meteringconfig_tls_root_ca_key: "{{ root_ca_secret_buf.resources[0].data['ca.key'] | b64decode }}"
      no_log: true

    - name: Add root CA certificate to certificates directory
      copy:
        content: "{{ _meteringconfig_tls_root_ca_certificate }}"
        dest: "{{ certificates_dir.path }}/ca.crt"

    - name: Add root CA private key to certificates directory
      copy:
        content: "{{ _meteringconfig_tls_root_ca_key }}"
        dest: "{{ certificates_dir.path }}/ca.key"
    when: root_ca_secret_exists
  vars:
    root_ca_secret_exists: "{{ root_ca_secret_buf.resources is defined and root_ca_secret_buf.resources | length > 0 }}"
  when: meteringconfig_tls_enabled

#
# Generate the metering root certificate authority
#
- name: Setup the root certificate authority
  block:
  - name: Generate a RSA private key for the CA
    openssl_privatekey:
      size: 2048
      type: RSA
      path: "{{ certificates_dir.path }}/ca.key"

  - name: Generate a CSR for the CA
    openssl_csr:
      path: "{{ certificates_dir.path }}/ca.csr"
      privatekey_path: "{{ certificates_dir.path }}/ca.key"
      common_name: Operator Metering Root CA
      use_common_name_for_san: false
      basicConstraints:
      - 'CA:TRUE'
      basicConstraints_critical: true

  - name: Generate a certificate for the CA
    openssl_certificate:
      path: "{{ certificates_dir.path }}/ca.crt"
      privatekey_path: "{{ certificates_dir.path }}/ca.key"
      csr_path: "{{ certificates_dir.path }}/ca.csr"
      provider: selfsigned
      selfsigned_digest: sha256

  - name: Use the generated root certificate authority cert/key values
    set_fact:
      _meteringconfig_tls_root_ca_certificate: "{{ lookup('file', '{{ certificates_dir.path }}/ca.crt') + '\n' }}"
      _meteringconfig_tls_root_ca_key: "{{ lookup('file', '{{ certificates_dir.path }}/ca.key') + '\n' }}"
    no_log: true
  vars:
    root_ca_secret_exists: "{{ root_ca_secret_buf.resources is defined and root_ca_secret_buf.resources | length > 0 }}"
  when: meteringconfig_tls_enabled and not root_ca_secret_exists
