---
- name: "Include web-app-discourse"
  include_role:
    name: web-app-discourse

- name: Wait for Discourse API
  wait_for:
    host: "{{ domains | get_domain('web-app-discourse') }}"
    port: 80
    delay: 5
    timeout: 600

- name: Add /var/www/discourse to Git safe.directory
  command: >
    docker exec {{ applications['web-app-discourse'].docker.services.discourse.name }} \
      git config --global --add safe.directory /var/www/discourse
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  changed_when: false

- name: Revoke old WP Discourse API keys via Rails
  command: >
    docker exec {{ applications['web-app-discourse'].docker.services.discourse.name }} bash -lc "\
      cd /var/www/discourse && \
      script/rails runner \"\
        ApiKey.where(\
          user_id: User.find_by_username('system').id,\
          description: 'WP Discourse Integration',\
          revoked_at: nil\
        ).update_all(revoked_at: Time.current)\
      \""
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  changed_when: false
  failed_when: false

- name: Generate new WP Discourse API key via Rake task
  command: >
    docker exec {{ applications['web-app-discourse'].docker.services.discourse.name }} bash -lc "\
      cd /var/www/discourse && \
      bin/rake api_key:create_master['WP Discourse Integration']\
    "
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: discourse_generated_api_key

- name: Store the new WP Discourse API key in a fact
  set_fact:
    vault_discourse_api_key: "{{ discourse_generated_api_key.stdout | trim }}"

- name: "Load WP Discourse settings"
  include_vars:
    file: "{{ role_path }}/vars/discourse.yml"

- name: "Install WP Discourse plugin"
  command: >
    docker-compose exec -u www-data -T application
      wp plugin install wp-discourse --activate
      --path={{ wordpress_docker_html_path }}
  args:
    chdir: "{{ docker_compose.directories.instance }}"

- name: "Configure WP Discourse settings"
  loop: "{{ discourse_settings | map(attribute='name') | unique | list }}"
  loop_control:
    label: "{{ item }}"
  vars:
    option_name: "{{ item }}"

    option_items: >-
      {{ discourse_settings
         | selectattr('name', 'equalto', option_name)
         | list
      }}

    option_kv: >-
      {{ dict(
           option_items | map(attribute='key')
           | zip(option_items | map(attribute='value'))
         ) }}

    option_json_b64: "{{ option_kv | to_json | b64encode }}"

  command: >
    docker-compose exec -u www-data -T application bash -lc
      "wp eval \"update_option(
         '{{ option_name }}',
         json_decode(
           base64_decode('{{ option_json_b64 }}'),
           true
         )
       );\" --path={{ wordpress_docker_html_path }}"
  args:
    chdir: "{{ docker_compose.directories.instance }}"