---
- block:
    - name: Add the repository
      apt_repository:
        state: present
        codename: "{{ ansible_distribution_release }}"
        repo: ppa:shevchuk/dnscrypt-proxy
      register: result
      until: result is succeeded
      retries: 10
      delay: 3

    - name: Configure unattended-upgrades
      copy:
        src: 50-dnscrypt-proxy-unattended-upgrades
        dest: /etc/apt/apt.conf.d/50-dnscrypt-proxy-unattended-upgrades
        owner: root
        group: root
        mode: 0644
  when: ansible_facts['distribution_version'] is version('20.04', '<')

- name: Install dnscrypt-proxy
  apt:
    name: dnscrypt-proxy
    state: present
    update_cache: true

- block:
    - name: Ubuntu | Configure AppArmor policy for dnscrypt-proxy
      copy:
        src: apparmor.profile.dnscrypt-proxy
        dest: /etc/apparmor.d/usr.bin.dnscrypt-proxy
        owner: root
        group: root
        mode: 0600
      notify: restart dnscrypt-proxy

    - name: Ubuntu | Enforce the dnscrypt-proxy AppArmor policy
      command: aa-enforce usr.bin.dnscrypt-proxy
      changed_when: false
  tags: apparmor
  when: apparmor_enabled|default(false)|bool

- name: Ubuntu | Ensure that the dnscrypt-proxy service directory exist
  file:
    path: /etc/systemd/system/dnscrypt-proxy.service.d/
    state: directory
    mode: 0755
    owner: root
    group: root

- name: Ubuntu | Add custom requirements to successfully start the unit
  copy:
    dest: /etc/systemd/system/dnscrypt-proxy.service.d/99-algo.conf
    content: |
      [Unit]
      After=systemd-resolved.service
      Requires=systemd-resolved.service

      [Service]
      AmbientCapabilities=CAP_NET_BIND_SERVICE
  notify:
    - restart dnscrypt-proxy
