# Copyright 2022 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
---

- name: Get grafana service IP
  command: kubectl get svc "{{ grafana_k8s }}" -n "{{ grafana_namespace }}" -o=jsonpath='{.spec.clusterIP}'
  changed_when: false
  register: grafana_svc_ip

- name: Get grafana service port
  command: kubectl get svc "{{ grafana_k8s }}" -n "{{ grafana_namespace }}" -o=jsonpath='{.spec.ports[0].port}'
  changed_when: false
  register: grafana_svc_port

- name: Get timescaleDB svc IP
  command: kubectl get svc "{{ timescaledb_k8s_name }}" -n "{{ namespace }}" -o=jsonpath='{.spec.clusterIP}'
  changed_when: false
  register: timescale_svc_ip

- name: Get timescaleDB svc port
  command: kubectl get svc "{{ timescaledb_k8s_name }}" -n "{{ namespace }}" -o=jsonpath='{.spec.ports[0].port}'
  changed_when: false
  register: timescale_svc_port

- name: Wait for grafana pod to come to ready state
  command: kubectl wait --for=condition=ready --timeout=10m -n "{{ grafana_namespace }}" pod -l app="{{ grafana_k8s }}"
  changed_when: false

- name: Add timescale datasource on grafana
  community.grafana.grafana_datasource:
    name: telemetry-postgres
    grafana_url: "http://{{ grafana_svc_ip.stdout }}:{{ grafana_svc_port.stdout }}"
    grafana_user: "{{ grafana_username }}"
    grafana_password: "{{ grafana_password }}"
    ds_type: "postgres"
    database: "{{ timescaledb_name }}"
    ds_url: "{{ timescale_svc_ip.stdout }}:{{ timescale_svc_port.stdout }}"
    user: "{{ timescaledb_user }}"
    sslmode: "disable"
    additional_json_data:
      postgresVersion: 12+
      timescaledb: true
    additional_secure_json_data:
      password: "{{ timescaledb_password }}"
  no_log: true