# -*- mode: yaml; indent-tabs-mode: nil; tab-width: 2; coding: utf-8-unix -*-

---

- block:

  - name: "/etc/NetworkManager/pre-up.d/"
    file:
      dest: "{{ item }}"
      state: directory
      mode:  0755
      owner: "{{BOX_ROOT_USER}}" # required
    with_items:
      - /etc/NetworkManager/dispatcher.d/pre-up.d/

  # what about -resolvconf on Gentoo?
  # see /etc/resolvconf/update.d/dnsmasq on Debian
  # see /etc/dhcp/dhclient-exit-hooks.d/ntpdate on Debian
  # see also etc/network/if-down.d/ on Debian
  # and etc/ppp/ip-down.d/
  - name: "/etc/NetworkManager/dispatcher.d/20-resolv-conf-override"
    lineinfile:
      path: /etc/NetworkManager/dispatcher.d/20-resolv-conf-override
      create: yes
      mode: 0755
      insertafter: BOF
      line: "#!/bin/sh"
      regexp: "#./bin/sh"

  - name: "/etc/NetworkManager/dispatcher.d/20-resolv-conf-override dnscrypt"
    blockinfile:
      path: /etc/NetworkManager/dispatcher.d/20-resolv-conf-override
      create: yes
      mode: 0755
      marker: "# {mark} ANSIBLE MANAGED BLOCK proxy dnscrypt"
      block: |
        [ -f /etc/resolv.conf.localhost ] || echo nameserver 127.0.0.1 > /etc/resolv.conf.localhost
        [ -f /etc/resolv.conf.dnscrypt ] && \
          [ -d /run/resolvconf ] && \
          cp -f /etc/resolv.conf.dnscrypt /run/resolvconf/resolv.conf
        exit 0
      state: "{{ 'present' if PROXY_DNS_PROXY == 'dnscrypt' else 'absent' }}"

  - name: "/etc/NetworkManager/dispatcher.d/20-resolv-conf-override dnscrypt"
    blockinfile:
      path: /etc/NetworkManager/dispatcher.d/20-resolv-conf-override
      create: yes
      mode: 0755
      marker: "# {mark} ANSIBLE MANAGED BLOCK proxy dnsmasq"
      state: "{{ 'present' if PROXY_DNS_PROXY == 'dnsmasq' else 'absent' }}"
      block: |
        [ -f /etc/resolv.conf.localhost ] || echo nameserver 127.0.0.1 > /etc/resolv.conf.localhost

        diff -q /etc/resolv.conf.localhost /etc/resolv.conf || \
          cp -f /etc/resolv.conf.localhost /etc/resolv.conf

        [ -d /run/resolvconf ] && \
          cp -f /etc/resolv.conf.localhost /run/resolvconf/resolv.conf

        [ -f /etc/resolvconf.conf ] || cat > /etc/resolvconf.conf <<EOF
        resolvconf=no
        name_servers=127.0.0.1
        resolv_conf=/etc/resolv.conf
        EOF

        exit 0


  #? FixMe: link to wicd/scripts - WHY pre-up? was dest/src swapped
  - name: "/etc/NetworkManager/dispatcher.d/20-resolv-conf-override link"
    file:
      src:  /etc/NetworkManager/dispatcher.d/20-resolv-conf-override
      dest: /etc/NetworkManager/dispatcher.d/pre-up.d/20-resolv-conf-override
      state: "{{'link' if PROXY_DNS_PROXY in ['dnscrypt', 'dnsmasq'] else 'absent'}}"
    when:
      - not ansible_check_mode

  when: PROXY_DNS_NETMAN == 'networkmanager'

# wicd
