---
- name: fetch logs from remote machines
  hosts: all
  ignore_unreachable: yes
  max_fail_percentage: 10
  tasks:
    # Due to the logs being continually written to, they must first be copied to a temp directory.
    # Otherwise the `fetch` task will produce checksum errors.
    - name: create temporary directory for logs
      command: mktemp -d
      register: temp_dir

    - name: copy all logs to temporary directory
      shell: |
        for file in $(find /home/safe/.local/share/safe/node/ -name "safenode.log" -o -name "safenode.log*" -o -name "*.log"); do
          cp $file {{ temp_dir.stdout }}
        done
      when: resources_only == "false"

    - name: copy all resource logs to temporary directory
      shell: |
        for file in $(find /home/safe/.local/share/safe/node/ -name "resource-usage.log"); do
          cp $file {{ temp_dir.stdout }}
        done
      when: resources_only == "true"

    - name: retrieve list of log files from temporary directory
      shell: find {{ temp_dir.stdout }} -name "*.log" -o -name "*.log*" -o -name "safenode.log*"
      register: find_result
      when: resources_only == "false"

    - name: retrieve list of resource.log files from temporary directory
      shell: find {{ temp_dir.stdout }} -name "resource-usage.log"
      register: find_result_resource_only
      when: resources_only == "true"

    - name: fetch each log file
      fetch:
        src: "{{ item }}"
        dest: "../../logs/{{env_name}}/"
        flat: no
      with_items: "{{ find_result.stdout_lines }}"
      when: resources_only == "false"

    - name: fetch resource file
      fetch:
        src: "{{ item }}"
        dest: "../../logs/{{env_name}}/"
        flat: no
      with_items: "{{ find_result_resource_only.stdout_lines }}"
      when: resources_only == "true"

    - name: remove temporary directory
      command: rm -rf {{ temp_dir.stdout }}

- name: reorganise local log files
  hosts: localhost
  max_fail_percentage: 10
  ignore_unreachable: yes
  tasks:
    - name: reorganise local log files
      command: python3 ../scripts/reorganise_logs.py "{{ env_name }}"
