- name: Update DB host
  command: >
    docker exec --user root {{ espocrm_name }}
    sed -i "s/'host' => .*/'host' => '{{ database_host }}',/" {{ espocrm_config_file }}
  notify: docker compose restart

- name: Update DB name
  command: >
    docker exec --user root {{ espocrm_name }}
    sed -i "s/'dbname' => .*/'dbname' => '{{ database_name }}',/" {{ espocrm_config_file }}
  notify: docker compose restart

- name: Update DB user
  command: >
    docker exec --user root {{ espocrm_name }}
    sed -i "s/'user' => .*/'user' => '{{ database_username }}',/" {{ espocrm_config_file }}
  notify: docker compose restart

- name: Update DB password
  command: >
    docker exec --user root {{ espocrm_name }}
    sed -i "s/'password' => .*/'password' => '{{ database_password }}',/" {{ espocrm_config_file }}
  notify: docker compose restart
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: Ensure siteUrl matches canonical domain
  ansible.builtin.shell: |
    docker compose exec -T web php -r '
      require "/var/www/html/bootstrap.php";
      $app = new \Espo\Core\Application();
      $c   = $app->getContainer();
      $cfg = $c->get("config");
      $writer = $c->get("injectableFactory")->create("\Espo\Core\Utils\Config\ConfigWriter");
      $new = "{{ espocrm_url }}";
      if ($cfg->get("siteUrl") !== $new) {
        $writer->set("siteUrl", $new);
        $writer->save();
        echo "CHANGED";
      }
    '
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: siteurl_set
  changed_when: "'CHANGED' in siteurl_set.stdout"