---

- name: Fail if playbook called incorrectly
  ansible.builtin.fail:
    msg: "The `username` variable needs to be provided to this playbook, via --extra-vars"
  when: "username is not defined or username == '<your-username>'"

- name: Fail if playbook called incorrectly
  ansible.builtin.fail:
    msg: "The `password` variable needs to be provided to this playbook, via --extra-vars"
  when: "password is not defined or password == '<your-password>'"

- name: Fail if not using integrated Postgres database
  ansible.builtin.fail:
    msg: "This command is working only when Postgres is installed via the the integrated ansible-role-postgres role"
  when: "not postgres_enabled | bool"

- name: Ensure Postgres is started
  ansible.builtin.service:
    name: "{{ postgres_identifier }}"
    state: started
    daemon_reload: true
  register: postgres_start_result

- name: Ensure Synapse is started
  ansible.builtin.service:
    name: matrix-synapse
    state: started
    daemon_reload: true
  register: synapse_start_result

- name: Wait a while, so that Synapse and/or Postgres can manage to start
  ansible.builtin.pause:
    seconds: 7
  when: "synapse_start_result.changed or postgres_start_result.changed"

- name: Generate user password hash
  ansible.builtin.shell: "{{ devture_systemd_docker_base_host_command_docker }} exec matrix-synapse /usr/local/bin/hash_password -c /data/homeserver.yaml -p {{ password | quote }}"
  register: password_hash
  changed_when: false

- name: Generate user password-change SQL command
  ansible.builtin.set_fact:
    matrix_synapse_user_password_change_command: >-
      {{ postgres_bin_path }}/cli-non-interactive --dbname={{ matrix_synapse_database_database | quote }} -c "UPDATE users SET password_hash='{{ password_hash.stdout }}' WHERE name = '@{{ username }}:{{ matrix_domain }}'"

- name: Update user password hash
  ansible.builtin.command:
    cmd: "{{ matrix_synapse_user_password_change_command }}"
  register: matrix_synapse_update_user_password_result
  changed_when: matrix_synapse_update_user_password_result.rc == 0
  failed_when: "matrix_synapse_update_user_password_result.rc != 0 or matrix_synapse_update_user_password_result.stdout != 'UPDATE 1'"
