#  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: Install Nginx
  package:
    name: nginx
    state: present
  when: ansible_facts['distribution'] != opensuse_os_name

- name: Install Nginx
  zypper:
    name: nginx
    state: present
  when: ansible_facts['distribution'] == opensuse_os_name

- name: Get prometheus service IP
  command: kubectl get svc -l app=prometheus,component=server -o=jsonpath='{.items[0].spec.clusterIP}'
  changed_when: false
  register: prometheus_svc_ip

- name: Configure nginx.conf (1/2)
  replace:
    path: "{{ role_path }}/templates/nginx.conf.j2"
    regexp: '        server_name  .*'
    replace: "        server_name  {{ ansible_default_ipv4.address }};"
  delegate_to: localhost

- name: Configure nginx.conf (2/2)
  replace:
    path: "{{ role_path }}/templates/nginx.conf.j2"
    regexp: '          proxy_pass http://.*'
    replace: "          proxy_pass http://{{ prometheus_svc_ip.stdout }};"
  delegate_to: localhost

- name: Load nginx conf
  template:
    src: nginx.conf.j2
    dest: "{{ nginx_conf_file_path }}"
    mode: "{{ nginx_conf_file_mode }}"

- name: Validate nginx conf file
  command: nginx -t
  changed_when: false

- name: Start and enable nginx service
  service:
    name: nginx
    state: restarted
    enabled: yes

- name: Create prometheus datasource in grafana
  community.grafana.grafana_datasource:
    name: "hpc-prometheus-{{ ansible_default_ipv4.address }}"
    grafana_url: "http://{{ grafana_svc_ip }}:{{ grafana_svc_port }}"
    grafana_user: "{{ hostvars['127.0.0.1']['grafana_username'] }}"
    grafana_password: "{{ hostvars['127.0.0.1']['grafana_password'] }}"
    ds_type: prometheus
    ds_url: "http://{{ ansible_default_ipv4.address }}:{{ nginx_listen_port }}"
    access: direct
  delegate_to: localhost
  no_log: true