---
- name: (agent5) Create Datadog agent config directory
  file:
    dest: /etc/dd-agent
    state: directory
    mode: 0755
  when: datadog_manage_config

- name: (agent5) Create main Datadog agent configuration file
  template:
    src: datadog.conf.j2
    dest: /etc/dd-agent/datadog.conf
    owner: "{{ datadog_user }}"
    group: "{{ datadog_group }}"
    mode: 0644 #FIXME: should have permissions set to only be readable by owner
  when: datadog_manage_config
  notify: restart datadog-agent

- name: (agent5) Ensure datadog-agent is running
  service:
    name: datadog-agent
    state: started
    enabled: yes
  when: not datadog_skip_running_check and datadog_enabled and not ansible_check_mode

- name: (agent5) Ensure datadog-agent is not running
  service:
    name: datadog-agent
    state: stopped
    enabled: no
  when: not datadog_skip_running_check and not datadog_enabled

- name: Register all checks files present in datadog
  find:
    paths: /etc/dd-agent/conf.d/
    patterns:
    - "*.yaml"
    file_type: file
  register: datadog_conf_files
  when: datadog_manage_config and datadog_disable_untracked_checks

- name: Register all checks files present in datadog
  find:
    paths: /etc/dd-agent/conf.d/
    patterns:
    - "*.yaml.default"
    file_type: file
  register: datadog_conf_files_default
  when: datadog_manage_config and datadog_disable_default_checks

- name: Delete checks not present in datadog_tracked_checks
  file:
    path: "/etc/dd-agent/conf.d/{{ item }}.yaml"
    state: absent
  loop: "{{ datadog_conf_files.files | map(attribute='path') | list | map('basename') | list | map('regex_replace', '^(.*).yaml$', '\\1') | list }}"
  when: datadog_manage_config and datadog_disable_untracked_checks and item not in datadog_tracked_checks
  notify: restart datadog-agent

- name: Delete default checks
  file:
    path: "/etc/dd-agent/conf.d/{{ item }}.yaml.default"
    state: absent
  loop: "{{ datadog_conf_files_default.files | map(attribute='path') | list
             | map('basename') | list | map('regex_replace', '^(.*).yaml.default$', '\\1') | list }}"
  when: datadog_manage_config and datadog_disable_default_checks and item not in datadog_tracked_checks
  notify: restart datadog-agent

- name: (agent5) Create a configuration file for each Datadog check
  template:
    src: checks.yaml.j2
    dest: "/etc/dd-agent/conf.d/{{ item }}.yaml"
    owner: "{{ datadog_user }}"
    group: "{{ datadog_group }}"
    mode: 0644 #FIXME: should have permissions set to only be readable by owner
  with_items: "{{ datadog_checks|list }}"
  when: datadog_manage_config
  notify: restart datadog-agent
