---
- name: Install packages
  apt:
    name: "{{ item }}"
    dpkg_options: 'force-confdef,force-confnew'
    update_cache: yes
  with_items:
    - opendkim
    - opendkim-tools
    - opendmarc

- name: Create directories folder in /etc
  file:
    path: "/etc/{{ item }}"
    state: directory
  with_items:
    - opendkim
    - opendmarc

- name: Create key with opendkim-genkey
  shell: "opendkim-genkey -b 2048 -d {{ domain }} -s {{ domain }}.dkim"
  args:
    chdir: /root/

- name: Move private dkim key
  command: "mv /root/{{ domain }}.dkim.private /etc/opendkim/"

- name: Update private key permissions
  file:
    path: "/etc/opendkim/{{ domain }}.dkim.private"
    mode: 0600

- name: Copy conf files to remote
  template:
    src: "{{ item.name}}"
    dest: "{{ item.dest }}"
  with_items:
    - {name: 'opendkim.conf.j2', dest: '/etc/opendkim.conf'}
    - {name: 'internalhosts.j2', dest: '/etc/opendkim/internalhosts'}
    - {name: 'trustedhosts.j2', dest: '/etc/opendkim/trustedhosts'}
    - {name: 'opendmarc.conf.j2', dest: '/etc/opendmarc.conf'}
    - {name: 'opendkim.j2', dest: '/etc/default/opendkim'}
    - {name: 'opendmarc.j2', dest: '/etc/default/opendmarc'}

- name: Add domain to signing table file
  lineinfile:
    path: /etc/opendkim/signingtable
    state:  present
    create: yes
    line: "*@{{ domain }} {{ domain }}"

- name: Add configuration to key table file
  lineinfile:
    path: /etc/opendkim/keytable
    state:  present
    create: yes
    line: "{{ domain }} {{ domain }}:mail:/etc/opendkim/{{ domain }}.dkim.private"

- name: Create log file
  file:
    path: "/var/log/{{ item }}.log"
    state: touch
    owner: "{{ item }}"
    group: "{{ item }}"
  with_items:
    - opendmarc

- name: Add items to ignore hosts
  blockinfile:
    path: /etc/opendmarc/ignore.hosts
    create: yes
    insertafter: EOF
    content: |
      localhost
      127.0.0.0/8
      174.128.244.233
      174.128.244.234
