---

# Pre-checks

- name: Fail if Postgres not enabled
  fail:
    msg: "Postgres via the matrix-postgres role is not enabled (`matrix_postgres_enabled`). Cannot run vacuum."
  when: "not matrix_postgres_enabled|bool"


# Defaults

- name: Set postgres_start_wait_time, if not provided
  set_fact:
    postgres_start_wait_time: 15
  when: "postgres_start_wait_time|default('') == ''"

- name: Set postgres_vacuum_wait_time, if not provided
  set_fact:
    postgres_vacuum_wait_time: "{{ 7 * 86400 }}"
  when: "postgres_vacuum_wait_time|default('') == ''"


# Actual vacuuming work

- name: Ensure matrix-postgres is started
  service:
    name: matrix-postgres
    state: started
    daemon_reload: yes

- name: Wait a bit, so that Postgres can start
  wait_for:
    timeout: "{{ postgres_start_wait_time }}"
  delegate_to: 127.0.0.1
  become: false

- import_tasks: tasks/util/detect_existing_postgres_version.yml

- name: Abort, if no existing Postgres version detected
  fail:
    msg: "Could not find existing Postgres installation"
  when: "not matrix_postgres_detected_existing|bool"

- name: Generate Postgres database vacuum command
  set_fact:
    matrix_postgres_vacuum_command: >-
      {{ matrix_host_command_docker }} run --rm --name matrix-postgres-synapse-vacuum
      --user={{ matrix_user_uid }}:{{ matrix_user_gid }}
      --cap-drop=ALL
      --network={{ matrix_docker_network }}
      --env-file={{ matrix_postgres_base_path }}/env-postgres-psql
      {{ matrix_postgres_docker_image_latest }}
      psql -v ON_ERROR_STOP=1 -h matrix-postgres {{ matrix_synapse_database_database }} -c 'VACUUM FULL VERBOSE'

- name: Note about Postgres vacuum alternative
  debug:
    msg: >-
      Running vacuum with the following Postgres command: `{{ matrix_postgres_vacuum_command }}`.
      If this crashes, you can stop all processes (`systemctl stop matrix-*`),
      start Postgres only (`systemctl start matrix-postgres`)
      and manually run the above command directly on the server.

- name: Populate service facts
  service_facts:

- set_fact:
    matrix_postgres_synapse_was_running: "{{ ansible_facts.services['matrix-synapse.service']|default(none) is not none and ansible_facts.services['matrix-synapse.service'].state == 'running' }}"

- name: Ensure matrix-synapse is stopped
  service:
    name: matrix-synapse
    state: stopped
    daemon_reload: yes

- name: Run Postgres vacuum command
  command: "{{ matrix_postgres_vacuum_command }}"
  async: "{{ postgres_vacuum_wait_time }}"
  poll: 10
  register: matrix_postgres_synapse_vacuum_result

# Intentionally show the results
- debug: var="matrix_postgres_synapse_vacuum_result"

- name: Ensure matrix-synapse is started, if it previously was
  service:
    name: matrix-synapse
    state: started
    daemon_reload: yes
  when: "matrix_postgres_synapse_was_running|bool"