---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

# We run two servers listening different ports
# to be able to check replication (one server for master, another for replica).

- name: Install redis dependencies
  package:
    name: "{{ redis_packages[ansible_distribution] }}"
    state: latest
    policy_rc_d: "{{ 101 if ansible_facts.pkg_mgr == 'apt' else omit }}"
  notify: cleanup redis

- name: Install redis module
  pip:
    name: "{{ redis_module }}"
    extra_args: "-c {{ remote_constraints }}"
    state: present
  notify: cleanup redis

- name: Create redis directories
  file:                                                                                                                                                                                                 
    path: "{{ item }}"
    state: directory                                                                                                                                                                                    
    owner: redis
    group: redis
  loop:
  - "{{ master_datadir }}"
  - "{{ master_logdir }}"
  - "{{ replica_datadir }}"
  - "{{ replica_logdir }}"

- name: Create redis configs
  copy:
    dest: "{{ item.file }}"
    content: |
      daemonize yes
      port {{ item.port }}
      pidfile /var/run/redis_{{ item.port }}.pid
      logfile {{ item.logdir }}/redis.log
      dir {{ item.datadir }}
      requirepass {{ redis_password }}
      masterauth {{ redis_password }}
  loop:
  - file: "{{ master_conf }}"
    port: "{{ master_port }}"
    logdir: "{{ master_logdir }}"
    datadir: "{{ master_datadir }}"
  - file: "{{ replica_conf }}"
    port: "{{ replica_port }}"
    logdir: "{{ replica_logdir }}"
    datadir: "{{ replica_datadir }}"

- name: Start redis master
  shell: "{{ redis_bin[ansible_distribution] }} {{ master_conf }}"

- name: Start redis replica
  shell: "{{ redis_bin[ansible_distribution] }} {{ replica_conf }} --{% if old_redis %}slaveof{% else %}replicaof{% endif %} 127.0.0.1 {{ master_port }}"

- name: Wait for redis master to be started
  ansible.builtin.wait_for:
    host: 127.0.0.1
    port: "{{ master_port }}"
    state: started
    delay: 1
    connect_timeout: 5
    timeout: 30

- name: Wait for redis replica to be started
  ansible.builtin.wait_for:
    host: 127.0.0.1
    port: "{{ replica_port }}"
    state: started
    delay: 1
    connect_timeout: 5
    timeout: 30
