---
- name: Check if site is already installed.
  command: >
    {{ drush_path }} status bootstrap
    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: "('Successful' not in drupal_site_installed.stdout) and (drupalvm_database == '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
    --site-name="{{ drupal_site_name }}"
    --account-name={{ drupal_account_name }}
    --account-pass={{ drupal_account_pass }}
    --db-url={{ drupalvm_database }}://{{ drupal_db_user }}:{{ drupal_db_password }}@localhost/{{ drupal_db_name }}
    {{ drupal_site_install_extra_args | default([]) | join(" ") }}
    chdir={{ drupal_core_path }}
  notify: restart webserver
  when: "'Successful' not in drupal_site_installed.stdout"
  become: no

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