# This reset function is redundant, because the 'sys-scv-docker' role reset will take care of it
# anyhow lets keep this here for documentary purposes

- name: "Load database & docker-compose variables for reset"
  ansible.builtin.include_vars:
    file: "{{ item }}"
  loop:
    - "{{ playbook_dir }}/roles/docker-compose/vars/docker-compose.yml"
    - "{{ playbook_dir }}/roles/cmp-rdbms/vars/database.yml"

- name: Sanity check for required vars
  assert:
    that:
      - database_type is defined
      - applications is defined
      - docker_compose is defined
      - ports is defined
    fail_msg: "Load roles/docker-compose/vars/docker-compose.yml and set `database_type` first."

- name: "Disconnect DB container from Discourse networks"
  ansible.builtin.command:
    cmd: "docker network disconnect {{ discourse_network_item }} {{ database_host }}"
  loop:
    - "{{ DISCOURSE_NETWORK }}"
    - "{{ DISCOURSE_PG_NETWORK }}"
  loop_control:
    loop_var: discourse_network_item
    label: "{{ discourse_network_item }}"
  register: disc_net_disconnect
  changed_when: disc_net_disconnect.rc == 0
  failed_when: >
    disc_net_disconnect.rc != 0 and
    ('is not connected' not in (disc_net_disconnect.stderr | default('') | lower)) and
    ('no such network' not in (disc_net_disconnect.stderr | default('') | lower)) and
    ('no such container' not in (disc_net_disconnect.stderr | default('') | lower))

- name: "destroy container '{{ DISCOURSE_CONTAINER }}'"
  ansible.builtin.command:
    cmd: "./launcher destroy {{ DISCOURSE_CONTAINER }}"
    chdir: "{{ DISCOURSE_REPOSITORY_DIR }}"
  register: discourse_destroy
  changed_when: discourse_destroy.rc == 0
  failed_when: >
    discourse_destroy.rc != 0 and
    ('unable to change directory before execution' not in (discourse_destroy.msg | default('') | lower))
