# install fb when WP-CLI is not installed
#- name: check if WP-CLI is installed
#  shell: "ls {{ item.wordpress_wp_cli_install_dir }} | grep -q 'wp'"
#  register: check_wp_cli
#  failed_when: False
#  changed_when: False
#  with_items: wordpress_installs
#  tags: [configuration, wordpress, wordpress-core, wordpress-wp-cli-is-installed]

#- name: install db with file
#  shell: "mysql -u {{ item.item.dbuser }} -p{{ app.database.dbpass }} < files/init.sql"
#  with_items: check_wp_cli.results
#  when: wordpress_installs and item.rc != 0
#  tags: [configuration, wordpress, wordpress-db, wordpress-db-install]

# Download and install core
- name: check if wp is downloaded
  shell: "ls {{ item.path }} | grep -q 'wp-'"
  register: check_download
  failed_when: False
  changed_when: False
  with_items: wordpress_installs
  tags: [configuration, wordpress, wordpress-core, wordpress-is-downloaded]

- name: download wp files
  shell: "wp core download --path={{ item.item.path }} --allow-root"
  with_items: check_download.results
  when: wordpress_installs and item.rc != 0
  tags: [configuration, wordpress, wordpress-core, wordpress-downloaded]

# Create wp-config file to connect to the database
- name: create wp-config
  shell: "wp core config --allow-root --quiet --path='{{ item.path }}' --dbname='{{ item.dbname }}' --dbuser='{{ item.dbuser }}' --dbpass='{{ item.dbpass }}' --dbhost='{{ item.dbhost | default('localhost') }}'"
  args:
    creates: "{{ item.path }}/wp-config.php"
    chdir: "{{ item.path }}"
  with_items: wordpress_installs
  tags: [configuration, wordpress, wordpress-core, wordpress-configure]

- name: check if database is already installed
  shell: "wp --path='{{ item.path }}' core is-installed"
  register: check_installation
  failed_when: False
  changed_when: False
  with_items: wordpress_installs
  tags: [configuration, wordpress, wordpress-core, wordpress-is-installed, wordpress-update, wordpress-update-core]

# Insert data into database
- name: install wp database
  shell: "wp --path='{{ item.item.path }}' core install --url='{{ item.item.url }}' --title='{{ item.item.title }}' --admin_name='{{ item.item.admin_name | default('admin') }}' --admin_email='{{ item.item.admin_email }}' --admin_password='{{ item.item.admin_password }}'"
  with_items: check_installation.results
  when: wordpress_installs and item.rc != 0
  tags: [configuration, wordpress, wordpress-core, wordpress-install]

- name: check install
  shell: "wp --path='{{ item.path }}' core is-installed"
  changed_when: False
  with_items: wordpress_installs
  tags: [configuration, wordpress, wordpress-core, wordpress-install-check]
  
# Update core
- name: update wp core
  shell: "wp --path='{{ item.item.path }}' core update"
  with_items: check_installation.results
  when: wordpress_installs and item.rc == 0 and item.item.core_update == 1
  tags: [configuration, wordpress, wordpress-core, wordpress-update, wordpress-update-core]
