---

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

- name: Prepare data, dispatch job in isolated environment.
  hosts: all
  gather_facts: false
  vars:
    secret: "{{ lookup('pipe', 'cat ' + src + '/env/ssh_key') }}"
  collections:
    - ansible.posix

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

    - name: synchronize job environment with isolated host
      synchronize:
        copy_links: true
        src: "{{ src }}"
        dest: "{{ dest }}"
      when: ansible_kubectl_config is not defined

    - name: synchronize job environment with remote job container
      synchronize:
        copy_links: true
        src: "{{ src }}"
        dest: "{{ dest }}"
        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

    - local_action: stat path="{{src}}/env/ssh_key"
      register: key

    - name: create a named pipe for secret environment data
      command: "mkfifo {{src}}/env/ssh_key"
      when: key.stat.exists

    - name: spawn the playbook
      command: "ansible-runner start {{src}} -p '{{playbook}}' -i {{ident}}"
      when: playbook is defined

    - name: spawn the adhoc command
      command: "ansible-runner start {{src}} -m {{module}} -a {{module_args}} -i {{ident}}"
      when: module is defined

    - name: write the secret environment data
      mkfifo:
        content: "{{secret}}"
        path: "{{src}}/env/ssh_key"
      when: key.stat.exists
      no_log: true
