---
# Disable IPv6 for Dovecot / force IPv4
- name: Create dovecot conf.d directory
  file:
    path: /etc/dovecot/conf.d
    state: directory

- name: Add dovecot conf
  lineinfile:
    path: /etc/dovecot/conf.d/99-ipv4-only.conf
    create: yes
    line: "listen = *"
    insertafter: EOF
    state: present

- name: Install dovecot
  apt:
    name: "{{ item }}"
    dpkg_options: 'force-confdef,force-confnew'
    update_cache: yes
  with_items:
    - dovecot-antispam
    - dovecot-imapd

- name: Create directors for dovecot users
  shell: maildirmake.dovecot /etc/skel/"{{ item }}"
  with_items:
    - Maildir
    - Maildir/.Drafts
    - Maildir/.Sent
    - Maildir/.Trash
    - Maildir/.Templates

- name: Copy dovecot skel directory to users
  synchronize:
    src: /etc/skel/Maildir
    dest: "/home/{{ item }}/"
    recursive: yes
  delegate_to: "{{ inventory_hostname }}"
  with_items:
    - jebba
    - mailarchive

- name: Update Maildir folder permissions in users folder
  file:
    path: "/home/{{ item }}/Maildir"
    mode: 0700
    owner: "{{ item }}"
    group: "{{ item }}"
  with_items:
    - jebba
    - mailarchive

- name: Update users folder permissions
  file:
    path: "/home/{{ item }}"
    mode: og-rwx
  with_items:
    - jebba
    - mailarchive

- name: Update 10-auth.conf and 10-mail.conf
  lineinfile:
    path: "/etc/dovecot/conf.d/{{ item.conf }}"
    regexp: '{{ item.find }}'
    line: '{{ item.replace }}'
  with_items:
    - {find: '^.*?disable_plaintext_auth.*=.*', replace: 'disable_plaintext_auth = yes', conf: '10-auth.conf'}
    - {find: '^.*?auth_mechanisms.*=.*', replace: 'auth_mechanisms = plain login', conf: '10-auth.conf'}
    - {find: '^.*?mail_location.*', replace: 'mail_location = maildir:~/Maildir', conf: '10-mail.conf'}

- name: Copy conf files to remote
  template:
    src: "{{ item }}.j2"
    dest: "/etc/dovecot/conf.d/{{ item }}"
  with_items:
    - 10-master.conf
    - 10-ssl.conf
  notify:
    - restart dovecot