---
# The following variables will be set by the runner of this playbook:
# src: /tmp/some/path/private_data_dir/

- name: Poll for status of active job.
  hosts: all
  gather_facts: false
  collections:
    - ansible.posix

  tasks:
    - name: "Output job the playbook is running for"
      debug:
        msg: "Checking on job {{ job_id }}"

    - name: Determine if daemon process is alive.
      shell: "ansible-runner is-alive {{src}}"
      register: is_alive
      ignore_errors: true

    - name: Copy artifacts from the isolated host.
      synchronize:
        src: "{{src}}/artifacts/"
        dest: "{{src}}/artifacts/"
        mode: pull
        delete: true
        recursive: true
      when: ansible_kubectl_config is not defined

    - name: Copy daemon log from the isolated host
      synchronize:
        src: "{{src}}/daemon.log"
        dest: "{{src}}/daemon.log"
        mode: pull
      when: ansible_kubectl_config is not defined

    - name: Copy artifacts from pod
      synchronize:
        src: "{{src}}/artifacts/"
        dest: "{{src}}/artifacts/"
        mode: pull
        delete: true
        recursive: true
        set_remote_user: false
        rsync_opts:
          - "--blocking-io"
          - "--rsh=$RSH"
      environment:
        RSH: "oc rsh --config={{ ansible_kubectl_config }}"
      delegate_to: localhost
      when: ansible_kubectl_config is defined

    - name: Copy daemon log from pod
      synchronize:
        src: "{{src}}/daemon.log"
        dest: "{{src}}/daemon.log"
        mode: pull
        set_remote_user: false
        rsync_opts:
          - "--blocking-io"
          - "--rsh=$RSH"
      environment:
        RSH: "oc rsh --config={{ ansible_kubectl_config }}"
      delegate_to: localhost
      when: ansible_kubectl_config is defined

    - name: Fail if previous check determined that process is not alive.
      fail:
        msg: "isolated task is still running"
      when: "is_alive.rc == 0"
