---
- name: Install Prometheus Node Exporter
  hosts: all,!otsrvcibernetica,!rpi_ubuntu  # Exclude [otsrcibernetica] group
  become: yes  # Run tasks with elevated privileges (sudo)

  tasks:
    - name: Check if Node Exporter is installed
      ansible.builtin.stat:
        path: /usr/local/bin/node_exporter
      register: node_exporter_installed

    - name: Download Node Exporter if not installed
      ansible.builtin.get_url:
        url: https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-armv7.tar.gz  # Update URL for ARM architecture if needed
        dest: /tmp/node_exporter.tar.gz
      register: download_node_exporter
      #when: not node_exporter_installed.stat.exists
      ignore_errors: true

    - name: Check if Node Exporter is downloaded
      ansible.builtin.stat:
        path: /tmp/node_exporter.tar.gz
      register: node_exporter_download

    - name: Copy local tar.gz file if download fails
      ansible.builtin.copy:
        src: /etc/prometheus/templates/node_exporter-1.7.0.linux-armv7.tar.gz
        dest: /tmp/node_exporter.tar.gz
      #when: not node_exporter_download.stat.exists

    - name: Extract Node Exporter
      ansible.builtin.unarchive:
        src: /tmp/node_exporter.tar.gz
        dest: /tmp
        remote_src: yes
      #when: not node_exporter_installed.stat.exists

    - name: Rename extracted folder to "node_exporter"
      ansible.builtin.shell: mv /tmp/node_exporter-*/node_exporter /usr/local/bin/node_exporter
      #when: not node_exporter_installed.stat.exists

    - name: Set permissions for Node Exporter
      ansible.builtin.file:
        path: /usr/local/bin/node_exporter
        owner: root
        group: root
        mode: 0755
      #when: not node_exporter_installed.stat.exists

    - name: Check if service is installed
      ansible.builtin.stat:
        path: /etc/systemd/system/node_exporter.service
      register: node_exporter_service_installed

    - name: Install unit file to systemd
      template:
        src: /etc/prometheus/templates/servicios/node_exporter.service.j2
        dest: /etc/systemd/system/node_exporter.service
        owner: root
        group: root
        mode: 0600
      #when: not node_exporter_service_installed.stat.exists

    - name: Configure Node Exporter systemd service
      systemd:
        name: node_exporter.service
        enabled: yes
        state: started
        daemon_reload: yes

    - name: Print messages based on results
      ansible.builtin.debug:
        msg: |
          {% if node_exporter_installed.stat.exists %}
          Node Exporter is already installed.
          {% else %}
          Node Exporter has been installed.
          {% endif %}
