---
# additional setup and fixes for OS dependent environment
- name: "[ENV] controls nextcloud_trusted_domain type"
  ansible.builtin.fail:
    msg: "New versions require nextcloud_trusted_domain to be declared as a list."
  when: nextcloud_trusted_domain is string

- name: "[ENV] - ca-certificate are up to date"
  # needed for downloading from download.nextcloud.com as the site use letsencrypt certificates
  # letsencrypt may not be trusted on older OS
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
    update_cache: true
    cache_valid_time: 86400
  loop:
    - acl
    - ca-certificates
  when: ansible_os_family in [ "Debian" ]

  # fix for debian not using sudo :
  # finding out if sudo is installed or not
- name: "[ENV] - Debian only : checking sudo."
  ansible.builtin.command: "dpkg -l sudo"
  changed_when: false
  register: nc_sudo_installed_result
  failed_when: false
  when: ansible_distribution == "Debian"

- name: "[ENV] - Checking su"
  block:
    - name: "[ENV] - rolling back to su."
      ansible.builtin.set_fact:
        ansible_become_method: "su"
    - name: "[ENV] - force su to use /bin/sh as shell"
      ansible.builtin.set_fact:
        ansible_become_flags: '-s /bin/sh'
  when:
    - nc_sudo_installed_result.rc is defined
    - nc_sudo_installed_result.rc != 0

- name: "[ENV] - Generate database user password."
  ansible.builtin.set_fact:
    nextcloud_db_pwd: "{{ lookup( 'ansible.builtin.password', 'nextcloud_instances/'+ nextcloud_instance_name +'/db_admin.pwd' ) }}"
  when: nextcloud_db_pwd is not defined

- name: "[ENV] - Generate database root password."
  ansible.builtin.set_fact:
    nextcloud_mysql_root_pwd: "{{ lookup( 'ansible.builtin.password', 'nextcloud_instances/'+ nextcloud_instance_name +'/db_root.pwd' ) }}"
  when:
    - nextcloud_db_backend in ["mysql", "mariadb"]
    - nextcloud_mysql_root_pwd is not defined
