---

- import_tasks: ../includes/webapps_webconf.yml
  vars:
    - app_id: bookstack_{{ bookstack_id }}
    - php_version: "{{ bookstack_php_version }}"
    - php_fpm_pool: "{{ bookstack_php_fpm_pool | default('') }}"
  tags: bookstack

- when: bookstack_app_key is not defined
  block:
    - name: Generate a uniq application key
      shell: /bin/php{{ bookstack_php_version }} {{ bookstack_root_dir }}/app/artisan key:generate --show > {{ bookstack_root_dir }}/meta/ansible_app_key
      args:
        creates: "{{ bookstack_root_dir }}/meta/ansible_app_key"

    - name: Read application key
      slurp: src={{ bookstack_root_dir }}/meta/ansible_app_key
      register: bookstack_rand_app_key

    - set_fact: bookstack_app_key={{ bookstack_rand_app_key.content | b64decode | trim }}

  tags: bookstack

- name: Deploy BookStack configuration
  template: src=env.j2 dest={{ bookstack_root_dir }}/app/.env group={{ bookstack_php_user }} mode=640
  tags: bookstack

- when: bookstack_install_mode != 'none'
  block:
    - name: Migrate the database
      shell: echo yes | /bin/php{{ bookstack_php_version }} {{ bookstack_root_dir }}/app/artisan migrate

    - name: Clear cache
      command: /bin/php{{ bookstack_php_version }} {{ bookstack_root_dir }}/app/artisan cache:clear

    - name: Clear views
      command: /bin/php{{ bookstack_php_version }} {{ bookstack_root_dir }}/app/artisan view:clear

    - name: Regenerate search
      command: /bin/php{{ bookstack_php_version }} {{ bookstack_root_dir }}/app/artisan bookstack:regenerate-search

  become_user: "{{ bookstack_php_user }}"
  tags: bookstack

- name: Deploy permission script
  template: src=perms.sh.j2 dest={{ bookstack_root_dir }}/perms.sh mode=755
  register: bookstack_perm_script
  tags: bookstack

- name: Apply permissions
  command: "{{ bookstack_root_dir }}/perms.sh"
  when: bookstack_perm_script.changed or bookstack_install_mode != 'none'
  tags: bookstack

- name: Deploy logrotate conf
  template: src=logrotate.conf.j2 dest=/etc/logrotate.d/bookstack_{{ bookstack_id }}
  tags: bookstack
