---
- name: check if autonomi binary exists
  ansible.builtin.stat:
    path: "{{ binary_dir }}/autonomi"
  register: autonomi_binary

- name: download the autonomi binary
  ansible.builtin.get_url:
    url: "{{ autonomi_archive_url }}"
    dest: "/tmp/{{ autonomi_archive_filename }}"
  when: not autonomi_binary.stat.exists

- name: extract the autonomi binary to /usr/local/bin
  ansible.builtin.unarchive:
    src: "/tmp/{{ autonomi_archive_filename }}"
    dest: "{{ binary_dir }}"
    remote_src: true
  become: true
  when: not autonomi_binary.stat.exists

- name: create safe users
  ansible.builtin.user:
    name: "safe{{ item }}"
    shell: /bin/bash
    state: present
  loop: "{{ range(1, autonomi_uploader_instances | int + 1) | list }}"

- name: copy upload-random-data.sh to remote for each safe user
  ansible.builtin.copy:
    src: upload-random-data.sh
    dest: "/home/safe{{ item }}/upload-random-data.sh"
    owner: "safe{{ item }}"
    group: "safe{{ item }}"
    mode: '0744'
  become: yes
  become_user: "safe{{ item }}"
  loop: "{{ range(1, autonomi_uploader_instances | int + 1) | list }}"

- name: create systemd service file
  ansible.builtin.template:
    src: autonomi_uploader.service.j2
    dest: "/etc/systemd/system/autonomi_uploader@.service"
    owner: root
    group: root
    mode: '0644'
  become: yes
  when: not autonomi_binary.stat.exists

- name: start and enable autonomi_uploader service for each uploader
  ansible.builtin.systemd:
    name: "autonomi_uploader@{{ item }}"
    state: started
    enabled: yes
  become: yes
  loop: "{{ range(1, autonomi_uploader_instances | int + 1) | list }}"
