---
- name: Create node_exporter user
  ansible.builtin.user:
    name: "{{ node_exporter_user }}"
    shell: /sbin/nologin
    create_home: false
    system: true
    state: present

- name: Create textfile collector directory
  ansible.builtin.file:
    path: "{{ node_exporter_textfile_dir }}"
    state: directory
    owner: "{{ node_exporter_user }}"
    group: "{{ node_exporter_user }}"
    mode: '0755'

- name: Download node_exporter
  ansible.builtin.get_url:
    url: "https://github.com/prometheus/node_exporter/releases/download/v{{ node_exporter_version }}/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
    dest: "/tmp/node_exporter-{{ node_exporter_version }}.tar.gz"
    mode: '0644'

- name: Extract node_exporter
  ansible.builtin.unarchive:
    src: "/tmp/node_exporter-{{ node_exporter_version }}.tar.gz"
    dest: /tmp/
    remote_src: true
    creates: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64/node_exporter"

- name: Install node_exporter binary
  ansible.builtin.copy:
    src: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64/node_exporter"
    dest: /usr/local/bin/node_exporter
    owner: root
    group: root
    mode: '0755'
    remote_src: true

- name: Deploy node_exporter systemd service
  ansible.builtin.template:
    src: node_exporter.service.j2
    dest: /etc/systemd/system/node_exporter.service
    mode: '0644'
  notify: Restart node_exporter

- name: Enable and start node_exporter
  ansible.builtin.systemd:
    name: node_exporter
    enabled: true
    state: started
    daemon_reload: true

- name: Open node_exporter port in nftables
  ansible.builtin.lineinfile:
    path: /etc/nftables.conf
    insertafter: '# prometheus'
    line: "    tcp dport {{ node_exporter_port }} accept comment \"node_exporter\""
    state: present
  notify: Reload nftables
  ignore_errors: true

- name: Deploy ROCm scraper script
  ansible.builtin.template:
    src: rocm_scraper.sh.j2
    dest: /usr/local/bin/rocm_scraper.sh
    mode: '0755'
  when: rocm_exporter_enabled

- name: Deploy ROCm scraper service + timer
  ansible.builtin.template:
    src: "{{ item }}.j2"
    dest: "/etc/systemd/system/{{ item }}"
    mode: '0644'
  loop:
    - rocm_scraper.service
    - rocm_scraper.timer
  when: rocm_exporter_enabled

- name: Enable ROCm scraper timer
  ansible.builtin.systemd:
    name: rocm_scraper.timer
    enabled: true
    state: started
    daemon_reload: true
  when: rocm_exporter_enabled
