---

- fail: msg="pg_admin_pass must be set"
  when: pg_admin_pass is not defined
  tags: ged

- include_vars: "{{ item }}"
  with_first_found:
    - vars/{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml
    - vars/{{ ansible_os_family }}-{{ ansible_distribution_major_version }}.yml
    - vars/{{ ansible_distribution }}.yml
    - vars/{{ ansible_os_family }}.yml
  tags: ged

- block:
    - import_tasks: ../includes/webapps_set_install_mode.yml
      vars:
        - root_dir: "{{ paperless_root_dir }}"
        - version: "{{ paperless_version }}"
    - set_fact: paperless_install_mode={{ (install_mode == 'upgrade' and not paperless_manage_upgrade) | ternary('none',install_mode) }}
    - set_fact: paperless_current_version={{ current_version | default('') }}
  tags: ged

# Create a random pass for the DB if needed
- when: paperless_db_pass is not defined
  block:
    - import_tasks: ../includes/get_rand_pass.yml
      vars:
        - pass_file: "{{ paperless_root_dir }}/meta/ansible_dbpass"
    - set_fact: paperless_db_pass={{ rand_pass }}
  tags: ged

# Create a random secret key
- when: paperless_secret_key is not defined
  block:
    - import_tasks: ../includes/get_rand_pass.yml
      vars:
        - pass_file: "{{ paperless_root_dir }}/meta/ansible_secret_key"
    - set_fact: paperless_secret_key={{ rand_pass }}
  tags: ged

# Create a random secret key
- when: paperless_admin_pass is not defined
  block:
    - import_tasks: ../includes/get_rand_pass.yml
      vars:
        - pass_file: "{{ paperless_root_dir }}/meta/ansible_admin_pass"
    - set_fact: paperless_admin_pass={{ rand_pass }}
  tags: ged

# Reset consumption dir to default if it doesn't exist
# This is useful when the consumption dir is from a network mount point but the mount
# isn't available yet when initializing paperless
- name: Check if consumption dir exists
  stat: path={{ paperless_consume_dir }}
  register: paperless_consume_dir_stat
  become_user: "{{ paperless_user }}" # we check if paperless has access, root could be denied when using a FUSE FS for example
  tags: ged

- name: Reset consumption dir to the default value
  set_fact: paperless_consume_dir={{ paperless_root_dir }}/consume
  when: not paperless_consume_dir_stat.stat.exists
  tags: ged
