---
- name: dovecot installation and configuration
  tags: dovecot
  become: true
  block:

  ###########################################
  ###   install dovecot with extensions   ###
  ###########################################
  - name: install dovecot
    ansible.builtin.apt:
      pkg:
        - dovecot-core
        - dovecot-imapd
        - dovecot-sieve
        - dovecot-managesieved
        - dovecot-ldap

  # add goup and user for dovecot vmail
  - name: dovecot addgroup vmail
    ansible.builtin.group:
      name: vmail
      gid: 1200

  - name: dovecot adduser vmail
    ansible.builtin.user:
      name: vmail
      comment: 'dovecot vmail user'
      uid: 1200
      group: vmail
      groups: dovecot

  - name: dovecot add dir /vol/mail/maildirs
    ansible.builtin.file:
      path: /vol/mail/maildirs
      state: directory
      owner: vmail
      group: vmail
      mode: '0770'

  - name: dovecot add dir /vol/mail/public
    ansible.builtin.file:
      path: /vol/mail/public
      state: directory
      owner: vmail
      group: vmail
      mode: '0770'

  #####################################
  ###   install ssl certs and key   ###
  #####################################
  - name: dovecot copy CA cert
    # certs do not need to live in "private". Debian does it like this.
    ansible.builtin.copy:
      src: ../../ldap/files/CA_PerFact_InternalIT.pem
      dest: /etc/dovecot/private/CA_PerFact_InternalIT.pem
      mode: '0644'
      owner: root
      group: root
    notify:
      - reload dovecot.service

  # certs and keys are locally stored in ./internalit/roles/ldap/files
  - name: dovecot copy SSL cert
    ansible.builtin.copy:
      src: "../../ldap/files/{{ inventory_hostname }}.perfact.de.pem"
      dest: "/etc/dovecot/private/{{ inventory_hostname }}.perfact.de.pem"
      mode: '0644'
      owner: dovecot
      group: dovecot
    notify:
      - reload dovecot.service

  # concatenate certcain
  - name: dovecot concatenate certchain
    shell: 'cat /etc/dovecot/private/{{ inventory_hostname }}.perfact.de.pem /etc/dovecot/private/CA_PerFact_InternalIT.pem > /etc/dovecot/private/certchain.pem'
    notify:
      - reload dovecot.service

  - name: dovecot copy SSL key
    ansible.builtin.copy:
      src: "../../ldap/files/{{ inventory_hostname }}.perfact.de.key"
      dest: "/etc/dovecot/private/{{ inventory_hostname }}.perfact.de.key"
      owner: dovecot
      group: dovecot
      mode: '0600'
    notify:
      - reload dovecot.service

  #################################
  ###   logging and logrotate   ###
  #################################
  - name: create /var/log/dovecot-lda.log
    ansible.builtin.file:
      path: /var/log/dovecot-lda.log
      state: touch
      owner: vmail
      group: vmail
      mode: '0660'

  # install rsyslog to allow conventional logging
  # starting with debian 12 rsyslog will no longer be installed
  - name: install rsyslog
    become: true
    ansible.builtin.package:
      name:
      - rsyslog
      state: present

  - name: dovecot configure rsyslog
    ansible.builtin.template:
      src: rsyslog/55-dovecot.conf
      dest: /etc/rsyslog.d/55-dovecot.conf
      owner: root
      group: root
      mode: '0644'
    notify:
      - restart rsyslog.service

  - name: configure logrotate for dovecot
    ansible.builtin.template:
      src: "logrotate/dovecot-perfact"
      dest: "/etc/logrotate.d/dovecot.perfact"
      owner: root
      group: root
      mode: '0644'
    notify: restart logrotate.service

  #############################
  ###   Configure dovecot   ###
  #############################
  # disable auth-system.conf to lookup only at ldap
  - name: disable auth-system.conf
    ansible.builtin.replace:
      dest: "/etc/dovecot/conf.d/10-auth.conf"
      regexp: '^\!include\sauth-system\.conf\.ext$'
      replace: '# disable auth-system.conf to lookup only at ldap\n# !include auth-system.conf.ext'

  # use own config files
  - name: dovecot copy setting for perfact mailserver
    ansible.builtin.template:
      src: "{{ item }}"
      dest: "/etc/dovecot/conf.d/"
    with_items:
      - 80-master.conf
      - 81-auth.conf
      - 820-auth-ldap.conf
      - 83-mailbox-location.conf
      - 84-ssl.conf
      - 85-imap-and-sieve.conf
      - 86-stats.conf
      - 87-shared-folders.conf
      - 89-logging.conf
    # some files dont exist yet - remove later:
    ignore_errors: true
    notify: reload dovecot.service

  - name: dovecot copy ldap setting must be root / 0600
    ansible.builtin.template:
      src: "821-dovecot-ldap.conf.ext"
      dest: "/etc/dovecot/"
      owner: 'root'
      group: 'root'
      mode: '0600'
    notify: reload dovecot.service
    # do not log passwords:
    diff: false

  - name: set public_mailboxes
    set_fact:
      public_mailboxes: >-
        {%- set publics = [] -%}
        {%- for key,value in other_mails.items() -%}
          {%- if 'public' in value -%}
            {%- if value.public == true -%}
              {{ publics.append( key ) }}
            {%- endif -%}
          {%- endif -%}
        {%- endfor -%}
        {{ publics }}

  #- name: debug public_mailboxes
  #  debug:
  #    msg: "{{ public_mailboxes }}"

  - name: create maildir if not exists
    shell: 'if [ ! -d /vol/mail/maildirs/{{ item }} ]; then /usr/bin/maildirmake.dovecot /vol/mail/maildirs/{{ item }} vmail; fi'
    with_items: "{{ public_mailboxes }}"

  - name: create links to /vol/mail/public/.MAILBOX
    ansible.builtin.file:
      src: "/vol/mail/maildirs/{{ item }}"
      dest: "/vol/mail/public/.{{ item }}"
      state: link
    with_items: "{{ public_mailboxes }}"

  # Copy initital ACL with admin users for new created public mailboxes.
  # ACLs have to be adjusted.
  # Local changes will never be overwritten. (force: false)
  - name: setup acls for public mailboxes with init settings if file not exitst
    ansible.builtin.copy:
      content: |
        # l lookup         Mailbox is visible in mailbox list. Mailbox can be
        #                  subscribed to.
        # r read           Mailbox can be opened for reading.
        # w write          Message flags and keywords can be changed, except Seen
        #                  and Deleted
        # s write-seen     Seen flag can be changed
        # t write-deleted  Deleted flag can be changed
        # i insert         Messages can be written or copied to the mailbox
        # p post           Messages can be posted to the mailbox by LDA, e.g. from
        #                  Pigeonhole Sieve Interpreter
        # e expunge        Messages can be expunged (deleted)
        # k create         Mailboxes can be created (or renamed) directly under this
        #                  mailbox (but not necessarily under its children, see ACL
        #                  Inheritance section above) (renaming also requires delete
        #                  rights)
        # x delete         Mailbox can be deleted
        # a admin          Administration rights to the mailbox (currently: ability
        #                  to change ACLs for mailbox)
        #
        # Initial setup with some admin users.
        # Please adjust manually!
        #
        user=skalinowski lrwtipksex
        user=bgaab       lrwtipkse
        user=thorsten    lrwtipksex
        user=ftasatan    lrwtipkse
      dest: "/vol/mail/public/.{{ item }}/dovecot-acl"
      mode: '0644'
      # file will only be transferred if the destination does not exist:
      force: false
    with_items: "{{ public_mailboxes }}"

# end block "tags dovecot" and "become true"
