- name: Create unarchivetest1 user
  user:
    name: unarchivetest1
    uid: 1002610001
    group: "{{ group_table[ansible_facts['distribution']] | default(omit) }}"
  register: user
  vars:
    group_table:
      MacOSX: staff

- name: Test unarchiving twice as unprivileged user
  become: yes
  become_user: unarchivetest1
  block:
    - name: prep our file
      copy:
        src: foo.txt
        dest: "{{ user.home }}/foo-unarchive.txt"
        mode: preserve

    - name: Prep a zip file as unarchivetest1 user
      shell: zip unarchivetest1-unarchive.zip foo-unarchive.txt
      args:
        chdir: "{{ user.home }}"
        creates: "{{ user.home }}/unarchivetest1-unarchive.zip"

    - name: create our zip unarchive destination as unarchivetest1 user
      file:
        path: "{{ user.home }}/unarchivetest1-unarchive-zip"
        state: directory

    - name: unarchive a zip file as unarchivetest1 user
      unarchive:
        src: "{{ user.home }}/unarchivetest1-unarchive.zip"
        dest: "{{ user.home }}/unarchivetest1-unarchive-zip"
        remote_src: yes
        list_files: True
      register: unarchive10

    - name: stat the unarchived file
      stat:
        path: "{{ user.home }}/unarchivetest1-unarchive-zip/foo-unarchive.txt"
      register: archive_path

    - name: verify that the tasks performed as expected
      assert:
        that:
          - unarchive10 is changed
          # Verify that file list is generated
          - "'files' in unarchive10"
          - "{{unarchive10['files']| length}} == 1"
          - "'foo-unarchive.txt' in unarchive10['files']"
          - archive_path.stat.exists

    - name: repeat the last request to verify no changes
      unarchive:
        src: "{{ user.home }}/unarchivetest1-unarchive.zip"
        dest: "{{ user.home }}/unarchivetest1-unarchive-zip"
        remote_src: yes
        list_files: True
      register: unarchive10b

    # Due to a bug in the date calculation used to determine if a change
    # was made or not, this check is unreliable. This seems to only happen on
    # Ubuntu 1604.
    # https://github.com/ansible/ansible/blob/58145dff9ca1a713f8ed295a0076779a91c41cba/lib/ansible/modules/unarchive.py#L472-L474
    - name: Check that unarchiving again reports no change
      assert:
        that:
          - unarchive10b is not changed
      ignore_errors: yes

  always:
    - name: remove our unarchivetest1 user and files
      user:
        name: unarchivetest1
        state: absent
        remove: yes
      become: no

    - name: Remove user home directory on macOS
      file:
        path: /Users/unarchivetest1
        state: absent
      become: no
      when: ansible_facts.distribution == 'MacOSX'
