---

- block:
  - name: Generate admin password
    command: 'apg -n 1 -m 16 -M lcN'
    register: nextcloud_admin_password_apg
    check_mode: no
    changed_when: False

  - debug:
      var: nextcloud_admin_password_apg

  - set_fact:
      nextcloud_admin_password: "{{ nextcloud_admin_password_apg.stdout }}"

  tags:
    - nextcloud
  when: nextcloud_admin_password == ""

- name: Get Nextcloud Status
  shell: "php ./occ status --output json | grep -v 'Nextcloud is not installed'"
  args:
    chdir: "{{ nextcloud_webroot }}"
  become_user: "{{ nextcloud_user }}"
  register: nc_status
  check_mode: no
  tags:
    - nextcloud

- name: Install Nextcloud
  command: "php ./occ maintenance:install --database mysql --database-name {{ nextcloud_db_name | mandatory }} --database-user {{ nextcloud_db_user | mandatory }} --database-pass {{ nextcloud_db_pass | mandatory }} --admin-user {{ nextcloud_admin_login | mandatory }} --admin-pass {{ nextcloud_admin_password | mandatory }} --data-dir {{ nextcloud_data | mandatory }}"
  args:
    chdir: "{{ nextcloud_webroot }}"
    creates: "{{ nextcloud_home }}/config/config.php"
  become_user: "{{ nextcloud_user }}"
  when: (nc_status.stdout | from_json).installed == false
  tags:
    - nextcloud

- name: Configure Nextcloud Mysql password
  replace:
    dest: "{{ nextcloud_home }}/nextcloud/config/config.php"
    regexp:  "'dbpassword' => '([^']*)',"
    replace: "'dbpassword' => '{{ nextcloud_db_pass }}',"
  tags:
    - nextcloud

- name: Configure Nextcloud cron
  cron:
    name: 'Nextcloud'
    minute: "*/5"
    job: "php -f {{ nextcloud_webroot }}/cron.php"
    user: "{{ nextcloud_user }}"
  tags:
    - nextcloud

- name: Erase previously trusted domains config
  command: "php ./occ config:system:set trusted_domains"
  args:
    chdir: "{{ nextcloud_webroot }}"
  become_user: "{{ nextcloud_user }}"
  tags:
    - nextcloud

- name: Configure trusted domains
  command: "php ./occ config:system:set trusted_domains {{ item.0 }} --value {{ item.1 }}"
  args:
    chdir: "{{ nextcloud_webroot }}"
  with_indexed_items:
    - "{{ nextcloud_domains }}"
  become_user: "{{ nextcloud_user }}"
  tags:
    - nextcloud

#- name: Configure memcache local to APCu
#  command: "php ./occ config:system:set memcache.local --value '\\OC\\Memcache\\APCu'"
#  args:
#    chdir: "{{ nextcloud_webroot }}"
#  become_user: "{{ nextcloud_user }}"
#  tags:
#    - nextcloud
