---
- name: Download... Download Nextcloud archive
  get_url:
    url:  "{{ NEXTCLOUD_URL }}"
    dest: /tmp/{{ NEXTCLOUD_TARBALL }}
    checksum: "sha256:{{ NEXTCLOUD_URL }}.sha256"

- name: Download... Download generic GPG key
  get_url:
    url: "{{ NEXTCLOUD_GPG }}"
    dest: /tmp/nextcloud.asc

- name: Download... Download Nextcloud release GPG key
  get_url:
    url: "{{ NEXTCLOUD_URL }}.asc"
    dest: /tmp/{{ NEXTCLOUD_TARBALL }}.asc

- name: Download... Import Nextcloud GPG key
  shell: gpg --import /tmp/nextcloud.asc

- name: Download... See Nextcloud GPG stored
  set_fact:
   correct_gpg: "{{ GPG_FINGERPRINT }}"

- name: Download... Verify Nextcloud GPG
  shell: gpg --verify /tmp/{{ NEXTCLOUD_TARBALL }}.asc /tmp/{{ NEXTCLOUD_TARBALL }} 2>&1 | tail -n 1 | cut -d ':' -f2 | tr -d ' '
  register: nc_fingerprint
  failed_when: (nc_fingerprint.stdout|string not in correct_gpg)

- name: Download... Extract Nextcloud
  unarchive:
    src: /tmp/{{ NEXTCLOUD_TARBALL }}
    dest: "{{ http_webroot }}"
    remote_src: true
    creates: "{{ http_webroot }}/nextcloud/occ"

- name: Download... Ensure Nextcloud files are 0640
  shell: find {{ http_webroot }}/nextcloud -type f -exec chmod -c 0640 {} \;
  register: nc_installation_chmod_result
  changed_when: "nc_installation_chmod_result.stdout != \"\""

- name: Download... Setting stronger directory ownership
  file:
    path: "{{ http_webroot }}/nextcloud/"
    recurse: true
    owner: "{{ nextcloud_websrv_user }}"
    group: "{{ nextcloud_websrv_group }}"
    state: directory

- name: Download... Ensure Nextcloud .htaccess and .user.ini are 0644 
  file:
    path: "{{ item }}"
    mode: u=rw,g=r,o=r
  with_items:
    - "{{ http_webroot }}/nextcloud/.htaccess"
    - "{{ http_webroot }}/nextcloud/.user.ini"

- name: Download... Remove Nextcloud tmp files
  ansible.builtin.file:
    path: "{{ item }}"
    state: absent
  with_items:
    - "/tmp/{{ NEXTCLOUD_TARBALL }}.asc"
    - "/tmp/{{ NEXTCLOUD_TARBALL }}"
    - "/tmp/nextcloud.asc"
