---
# --- Utilisateur système ---

- name: Create qdrant system user
  ansible.builtin.user:
    name: "{{ qdrant_user }}"
    system: true
    shell: /sbin/nologin
    home: "{{ qdrant_install_dir }}"
    create_home: true
    state: present

# --- Répertoires données (RAID5) ---

- name: Create Qdrant data directories on RAID5
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: "{{ qdrant_user }}"
    group: "{{ qdrant_user }}"
    mode: '0750'
  loop:
    - "{{ qdrant_data_dir }}"
    - "{{ qdrant_data_dir }}/storage"
    - "{{ qdrant_data_dir }}/snapshots"

# --- Binaire ---

- name: Check if qdrant binary is already installed
  ansible.builtin.stat:
    path: "{{ qdrant_install_dir }}/qdrant"
  register: qdrant_binary

- name: Check installed qdrant version
  ansible.builtin.command:
    cmd: "{{ qdrant_install_dir }}/qdrant --version"
  register: qdrant_current_version
  changed_when: false
  failed_when: false
  when: qdrant_binary.stat.exists

- name: Download qdrant binary
  ansible.builtin.get_url:
    url: "https://github.com/qdrant/qdrant/releases/download/v{{ qdrant_version }}/qdrant-x86_64-unknown-linux-musl.tar.gz"
    dest: /tmp/qdrant.tar.gz
    mode: '0644'
  when: >
    not qdrant_binary.stat.exists or
    qdrant_version not in (qdrant_current_version.stdout | default(''))

- name: Extract qdrant binary
  ansible.builtin.unarchive:
    src: /tmp/qdrant.tar.gz
    dest: "{{ qdrant_install_dir }}"
    remote_src: true
    owner: "{{ qdrant_user }}"
    group: "{{ qdrant_user }}"
  when: >
    not qdrant_binary.stat.exists or
    qdrant_version not in (qdrant_current_version.stdout | default(''))
  notify: Restart qdrant

# --- Configuration ---

- name: Deploy Qdrant config
  ansible.builtin.template:
    src: config.yaml.j2
    dest: "{{ qdrant_install_dir }}/config.yaml"
    owner: "{{ qdrant_user }}"
    group: "{{ qdrant_user }}"
    mode: '0640'
  notify: Restart qdrant

# --- Service systemd ---

- name: Deploy Qdrant systemd service
  ansible.builtin.template:
    src: qdrant.service.j2
    dest: /etc/systemd/system/qdrant.service
    mode: '0644'
  notify:
    - Restart qdrant

- name: Enable and start Qdrant
  ansible.builtin.systemd:
    name: qdrant
    enabled: true
    daemon_reload: true
    state: started

# Firewall géré centralement par le rôle gateway (nftables)
# Ports 6333 (HTTP) et 6334 (gRPC) ouverts pour cluster_network dans nftables.conf.j2
