---

- name: Install Grafana repository keys
  ansible.builtin.get_url:
    url: https://packages.grafana.com/gpg.key
    dest: /etc/apt/trusted.gpg.d/grafana.asc
    force: true
    owner: root
    group: root
    mode: "0644"
  tags:
    - packages
    - repo
    - grafana
    - config

- name: Install Grafana repo
  ansible.builtin.apt_repository:
    repo: "deb https://packages.grafana.com/enterprise/deb stable main"
  tags:
    - packages
    - repo
    - grafana
    - config

- name: Install Grafana
  ansible.builtin.apt:
    name:
      - grafana-enterprise
    state: present
  tags:
    - packages
    - grafana

- name: Create systemd unit override directory
  ansible.builtin.file:
    path: /etc/systemd/system/grafana-server.service.d
    state: directory
    owner: root
    group: root
    mode: "0755"
  tags:
    - grafana
    - config

- name: Configure Grafana systemd service
  ansible.builtin.copy:
    src: grafana-server-override.service
    dest: /etc/systemd/system/grafana-server.service.d/ansible-override.conf
    owner: root
    group: root
    mode: "0644"
  notify:
    - Reload systemd
    - Restart Grafana
  tags:
    - grafana
    - config

- name: Configure Grafana
  ansible.builtin.template:
    src: grafana.ini.j2
    dest: /etc/grafana/grafana.ini
    owner: root
    group: grafana
    mode: "0640"
  notify:
    - Restart Grafana
  tags:
    - config
    - grafana

- name: Configure Grafana LDAP auth
  ansible.builtin.template:
    src: ldap.toml.j2
    dest: /etc/grafana/ldap.toml
    owner: root
    group: grafana
    mode: "0640"
  when:
    - grafana_ldap
  notify:
    - Restart Grafana
  tags:
    - config
    - grafana

- name: Configure Postgres for Grafana
  ansible.builtin.import_tasks: postgres.yml
  when:
    - grafana_database is defined
    - grafana_database.type == "postgres"
    - grafana_database.host[0] == '/'
  tags:
    - grafana
    - postgres

- name: Flush handlers
  ansible.builtin.meta: flush_handlers

- name: Enable and start Grafana
  ansible.builtin.systemd:
    name: grafana-server.service
    state: started
    enabled: true
  tags:
    - grafana
