# This playbook retrieves data that Fedora knows about a username and/or e-mail address.
#
# Please read http://fedora-infra-docs.readthedocs.io/en/latest/sysadmin-guide/sops/gdpr_sar.html
# for information about how to use this playbook and how to integration applications with it.
- name: Create the archive location
  hosts: localhost
  tasks:
    - name: "Create the archive"
      block:
        # Create a safe place to store the files.
        - command: "mktemp -d"
          register: sar_tmp_dir
        # Let's make this a more conveniently expressed variable.
        - set_fact:
            sar_tmp_dir: "{{ sar_tmp_dir['stdout'] }}"

- name: Gather SAR data
  hosts: sar
  strategy: free
  tasks:
    # Non-huge SAR retrieval
    - command: "{{ sar_script }}"
      environment:
        SAR_USERNAME: "{{ sar_fas_user }}"
        SAR_EMAIL: "{{ sar_email }}"
      register: sar_data
      become: yes
      become_user: "{{ sar_script_user }}"
      when: "sar_huge is not defined or not sar_huge"
    # Store the result on disk
    - copy:
        content: "{{ sar_data['stdout'] }}"
        dest: "{{ hostvars['localhost']['sar_tmp_dir'] }}/{{ sar_output_file }}"
      delegate_to: localhost
      delegate_facts: false
      when: "sar_huge is not defined or not sar_huge"
    # Remove the variable from memory
    - command: "/bin/true"
      register: sar_data
      when: "sar_huge is not defined or not sar_huge"

    # Huge SAR retrieval
    - shell: "ssh {{ inventory_hostname }} sudo -u {{ sar_script_user }} SAR_USERNAME={{ sar_fas_user }} SAR_EMAIL={{ sar_email }} {{ sar_script }} >{{ hostvars['localhost']['sar_tmp_dir'] }}/{{ sar_output_file }}"
      delegate_to: localhost
      when: "sar_huge is defined and sar_huge"

- name: Gather SAR data - openshift apps
  hosts: os_masters[0]
  tasks:
    - include_tasks: sar_openshift.yml
      loop: "{{ lookup('dict', sar_openshift, wantlist=True) }}"

- name: Create the archive
  hosts: localhost
  tasks:
    - name: "Create the archive"
      block:
        # Generate a private tarball of the files from each service.
        - shell: "umask 0077 && tar --transform \"s:^:{{ sar_fas_user }}_{{ sar_email }}/:\" -czf {{ sar_tmp_dir }}/{{ sar_fas_user }}_{{ sar_email }}.tar.gz *"
          args:
            chdir: "{{ sar_tmp_dir }}"
        # Move the tarball into the desired pick up location.
        - command: "mv {{ sar_tmp_dir }}/{{ sar_fas_user }}_{{ sar_email }}.tar.gz {{ sar_tar_output_path }}"
      always:
        # Let's clean up our temporary directory.
        - command: "rm -r {{ sar_tmp_dir }}"
