---
- name: Create mail data directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: root
    mode: "0755"
  loop:
    - "{{ mail_data_dir }}"
  tags: mail

- name: Create Roundcube database directory (postgres UID 999)
  ansible.builtin.file:
    path: "{{ mail_data_dir }}/db"
    state: directory
    owner: "999"
    group: "999"
    mode: "0700"
  tags: mail

- name: Create Dovecot maildir (vmail UID 5000)
  ansible.builtin.file:
    path: "{{ mail_data_dir }}/maildir"
    state: directory
    owner: "5000"
    group: "5000"
    mode: "0755"
  tags: mail

- name: Deploy Dovecot config
  ansible.builtin.template:
    src: dovecot.conf.j2
    dest: "{{ mail_data_dir }}/dovecot.conf"
    owner: root
    group: root
    mode: "0644"
  notify: Restart mail
  tags: mail

- name: Deploy Dovecot passwd file
  ansible.builtin.template:
    src: passwd.j2
    dest: "{{ mail_data_dir }}/passwd"
    owner: root
    group: root
    mode: "0644"
  notify: Restart mail
  tags: mail

- name: Deploy fetchmail config
  ansible.builtin.template:
    src: fetchmailrc.j2
    dest: "{{ mail_data_dir }}/fetchmailrc"
    owner: root
    group: root
    mode: "0600"
  notify: Restart mail
  tags: mail

- name: Deploy Docker Compose file
  ansible.builtin.template:
    src: docker-compose.yml.j2
    dest: "{{ mail_data_dir }}/docker-compose.yml"
    owner: root
    group: root
    mode: "0644"
  notify: Restart mail
  tags: mail

- name: Start mail stack
  community.docker.docker_compose_v2:
    project_src: "{{ mail_data_dir }}"
    state: present
    pull: missing
  tags: mail
