---
- name: Check if site is already installed.
  command: "{{ drush_path }} --root={{ drupal_core_path }} status bootstrap"
  args:
    chdir: "{{ drupal_core_path }}"
  register: drupal_site_installed
  failed_when: "drupal_site_installed.stdout is undefined"
  changed_when: false
  become: no

# See: https://www.drupal.org/node/2569365#comment-11680807
- name: Configure database correctly if using PostgreSQL.
  command: psql -c "ALTER DATABASE {{ drupal_db_name }} SET bytea_output = 'escape';"
  when: "('Drupal bootstrap' not in drupal_site_installed.stdout) and (drupal_db_backend == 'pgsql')"
  become: yes
  become_user: "{{ postgresql_user }}"
  # See: https://github.com/ansible/ansible/issues/16048#issuecomment-229012509
  vars:
    ansible_ssh_pipelining: true

- name: Install Drupal with drush.
  command: >
    {{ drush_path }} site-install {{ drupal_install_profile | default('standard') }} -y
    --root={{ drupal_core_path }}
    --site-name="{{ drupal_site_name }}"
    --account-name={{ drupal_account_name }}
    --account-pass={{ drupal_account_pass }}
    --db-url={{ drupal_db_backend }}://{{ drupal_db_user }}:{{ drupal_db_password }}@{{ drupal_db_host }}/{{ drupal_db_name }}
    {{ drupal_site_install_extra_args | join(" ") }}
  args:
    chdir: "{{ drupal_core_path }}"
  notify: clear opcache
  when: "'Drupal bootstrap' not in drupal_site_installed.stdout"
  become: no

- name: Install configured modules with drush.
  command: >
    {{ drush_path }} pm-enable -y {{ drupal_enable_modules | join(" ") }}
    --root={{ drupal_core_path }}
  args:
    chdir: "{{ drupal_core_path }}"
  when: ('Drupal bootstrap' not in drupal_site_installed.stdout) and drupal_enable_modules
  become: no
