---
- name: Ensure that Hawkular has nodes to run on
  import_role:
    name: openshift_control_plane
    tasks_from: ensure_nodes_matching_selector.yml
  vars:
    openshift_master_ensure_nodes_selector: "{{ openshift_metrics_hawkular_nodeselector | map_to_pairs }}"
    openshift_master_ensure_nodes_service: Hawkular

- command: >
    {{ openshift_client_binary }} -n {{ openshift_metrics_project | quote }}
    --config={{ mktemp.stdout }}/admin.kubeconfig
    get rc hawkular-metrics -o jsonpath='{.spec.replicas}'
  register: hawkular_metrics_replica_count
  failed_when: false
  changed_when: false

- name: generate hawkular-metrics replication controller
  template:
    src: hawkular_metrics_rc.j2
    dest: "{{ mktemp.stdout }}/templates/hawkular_metrics_rc.yaml"
  vars:
    replica_count: "{{hawkular_metrics_replica_count.stdout | default(0)}}"
    node_selector: "{{openshift_metrics_hawkular_nodeselector | default('') }}"
  changed_when: false

- name: read hawkular-metrics route destination ca certificate
  slurp: src={{ mktemp.stdout }}/ca.crt
  register: metrics_route_dest_ca_cert
  changed_when: false

- block:
  - set_fact: hawkular_key={{ lookup('file', openshift_metrics_hawkular_key) }}
    when: openshift_metrics_hawkular_key is exists
    changed_when: false

  - set_fact: hawkular_cert={{ lookup('file', openshift_metrics_hawkular_cert) }}
    when: openshift_metrics_hawkular_cert is exists
    changed_when: false

  - set_fact: hawkular_ca={{ lookup('file', openshift_metrics_hawkular_ca) }}
    when: openshift_metrics_hawkular_ca is exists
    changed_when: false

  - name: generate the hawkular-metrics route
    template:
      src: route.j2
      dest: "{{ mktemp.stdout }}/templates/hawkular-metrics-route.yaml"
    vars:
      name: hawkular-metrics
      annotations: "{{ openshift_metrics_hawkular_route_annotations }}"
      labels:
        metrics-infra: hawkular-metrics
      host: "{{ openshift_metrics_hawkular_hostname }}"
      to:
        kind: Service
        name: hawkular-metrics
      tls:
        termination: reencrypt
        key: "{{ hawkular_key | default('') }}"
        certificate: "{{ hawkular_cert | default('') }}"
        ca_certificate: "{{ hawkular_ca | default('') }}"
        destination_ca_certificate: "{{ metrics_route_dest_ca_cert.content | b64decode }}"
    changed_when: false
