---

- ansible.builtin.set_fact:
    matrix_authentication_service_syn2mas_dry_run: "{{ matrix_authentication_service_syn2mas_dry_run | bool }}"

- name: Abort, if not using Synapse
  when: not matrix_synapse_enabled | bool
  ansible.builtin.fail:
    msg: |-
      You can only use syn2mas to migrate from Synapse to Matrix Authentication Service.
      Other homeserver implementations are not supported.

- name: Fail if required matrix-authentication-service syn2mas settings not defined
  ansible.builtin.fail:
    msg: >-
      You need to define a required configuration setting (`{{ item.name }}`).
  when: "item.when | bool and vars[item.name] | length == 0"
  with_items:
    - {'name': 'matrix_authentication_service_syn2mas_synapse_homeserver_config_path', when: true}

- name: Check if Synapse homeserver config file exists
  ansible.builtin.stat:
    path: "{{ matrix_authentication_service_syn2mas_synapse_homeserver_config_path }}"
  register: matrix_authentication_service_syn2mas_synapse_config_stat

- name: Fail if Synapse homeserver config file does not exist
  ansible.builtin.fail:
    msg: "The Synapse homeserver config file does not exist at the specified path: {{ matrix_authentication_service_syn2mas_synapse_homeserver_config_path }}"
  when: not matrix_authentication_service_syn2mas_synapse_config_stat.stat.exists

- name: Ensure Matrix Authentication Service syn2mas container image is pulled
  community.docker.docker_image:
    name: "{{ matrix_authentication_service_syn2mas_container_image }}"
    source: "{{ 'pull' if ansible_version.major > 2 or ansible_version.minor > 7 else omit }}"
    force_source: "{{ matrix_authentication_service_syn2mas_container_image_force_pull if ansible_version.major > 2 or ansible_version.minor >= 8 else omit }}"
    force: "{{ omit if ansible_version.major > 2 or ansible_version.minor >= 8 else matrix_authentication_service_syn2mas_container_image_force_pull }}"
  when: "not matrix_authentication_service_syn2mas_container_image_self_build | bool"
  register: result
  retries: "{{ devture_playbook_help_container_retries_count }}"
  delay: "{{ devture_playbook_help_container_retries_delay }}"
  until: result is not failed

- when: "matrix_authentication_service_syn2mas_container_image_self_build | bool"
  block:
    - name: Ensure Matrix Authentication Service repository is present on self-build
      ansible.builtin.git:
        repo: "{{ matrix_authentication_service_container_repo }}"
        version: "{{ matrix_authentication_service_container_repo_version }}"
        dest: "{{ matrix_authentication_service_container_src_files_path }}"
        force: "yes"
      become: true
      become_user: "{{ matrix_user_username }}"
      register: matrix_authentication_service_git_pull_results

    - name: Ensure Matrix Authentication Service syn2mas container image is built
      ansible.builtin.command:
        cmd: |-
          {{ devture_systemd_docker_base_host_command_docker }} buildx build
          --tag={{ matrix_authentication_service_syn2mas_container_image }}
          --file={{ matrix_authentication_service_container_src_files_path }}/tools/syn2mas/Dockerfile
          {{ matrix_authentication_service_container_src_files_path }}/tools/syn2mas
      changed_when: true

- name: Ensure Synapse is stopped
  when: not matrix_authentication_service_syn2mas_dry_run | bool
  ansible.builtin.service:
    name: matrix-synapse
    state: stopped
    daemon_reload: true
  register: matrix_authentication_service_synapse_ensure_stopped_result

# We probably don't necessarily need to stop this, because:
# - the upstream docs don't say we should.
# - while a migration is in progress (see `matrix_authentication_service_migration_in_progress`),
#   we don't even add compatibility layer labels, so MAS would not be used anyway.
#
# Still, it's probably safer to stop it anyway.
- name: Ensure Matrix Authentication Service is stopped
  ansible.builtin.service:
    name: matrix-authentication-service
    state: stopped
  register: matrix_authentication_service_mas_ensure_stopped_result

- name: Generate syn2mas migration command
  ansible.builtin.set_fact:
    matrix_authentication_service_syn2mas_migration_command: >-
      {{ devture_systemd_docker_base_host_command_docker }} run
      --rm
      --name=matrix-authentication-service-syn2mas
      --log-driver=none
      --user={{ matrix_authentication_service_uid }}:{{ matrix_authentication_service_gid }}
      --cap-drop=ALL
      --network={{ matrix_authentication_service_syn2mas_container_network }}
      --mount type=bind,src={{ matrix_authentication_service_syn2mas_synapse_homeserver_config_path }},dst=/homeserver.yaml,ro
      --mount type=bind,src={{ matrix_authentication_service_config_path }}/config.yaml,dst=/mas-config.yaml,ro
      {{ matrix_authentication_service_syn2mas_container_image }}
      --command=migrate
      --synapseConfigFile=/homeserver.yaml
      --masConfigFile=/mas-config.yaml
      {{ matrix_authentication_service_syn2mas_process_extra_arguments | join(' ') }}
      {% if matrix_authentication_service_syn2mas_dry_run | bool %}--dryRun{% endif %}
  tags:
    - skip_ansible_lint

# This is a hack.
# See: https://ansibledaily.com/print-to-standard-output-without-escaping/
#
# We want to run `debug: msg=".."`, but that dumps it as JSON and escapes double quotes within it,
# which ruins the command (`matrix_authentication_service_syn2mas_migration_command`)
- name: Note about syn2mas migration
  ansible.builtin.set_fact:
    dummy: true
  with_items:
    - >-
        Running syn2mas migration using the following command: `{{ matrix_authentication_service_syn2mas_migration_command }}`.
        If this crashes, you can stop Synapse (`systemctl stop matrix-synapse`) and run the command manually.

- name: Perform syn2mas migration
  ansible.builtin.command:
    cmd: "{{ matrix_authentication_service_syn2mas_migration_command }}"
  register: matrix_authentication_service_syn2mas_migration_command_result
  changed_when: matrix_authentication_service_syn2mas_migration_command_result.rc == 0

- name: Print syn2mas migration command result
  ansible.builtin.debug:
    var: matrix_authentication_service_syn2mas_migration_command_result

- name: Ensure Synapse is started (if it previously was)
  when: "not matrix_authentication_service_syn2mas_dry_run and matrix_authentication_service_synapse_ensure_stopped_result.changed"
  ansible.builtin.service:
    name: matrix-synapse
    state: started

- name: Ensure Matrix Authentication Service is started (if it previously was)
  when: "not matrix_authentication_service_syn2mas_dry_run and matrix_authentication_service_mas_ensure_stopped_result.changed"
  ansible.builtin.service:
    name: matrix-authentication-service
    state: started