---
# tasks file for pi-hole

- name: Pi-Hole setup
  block:
    - name: Populate service facts
      ansible.builtin.service_facts:

    - name: Start install process for pihole if service not found
      when: "ansible_facts.services['pihole-FTL.service'] is not defined"
      block:
        - name: Install cURL if not present
          ansible.builtin.package:
            name: curl

        - name: Execute manually the automated install and follow instructions, after that you can install custom list
          ansible.builtin.debug:
            msg: "curl -sSL https://install.pi-hole.net | bash"

    - name: Check if can install custom list
      when: 'pihole_install_custom_list is true'
      block:
        - name: Check if pi-hole db exists
          stat:
            path: /etc/pihole/gravity.db
          register: pihole_db

        - name: Install sqlite3 package
          ansible.builtin.package:
            name: sqlite3

        - name: Install more lists than default
          when: pihole_db.stat.exists
          ansible.builtin.shell:
            cmd: sqlite3 /etc/pihole/gravity.db "INSERT INTO adlist (address, enabled, comment) VALUES ('{{ item }}', 1, '');"
          loop: "{{ pihole_custom_list }}"

    - name: Update Gravity
      when: 'pihole_update_gravity is true'
      ansible.builtin.shell: pihole updateGravity

    - name: iptables-webserver
      ansible.builtin.include_role:
        name: iptables-webserver

    - name: Setup iptables rules
      ansible.builtin.iptables:
        chain: INPUT
        protocol: '{{ item }}'
        destination_port: 53
        jump: ACCEPT
        comment: Accept DNS connections
      loop: [tcp,udp]

    - name: iptables-persistent
      ansible.builtin.include_role:
        name: iptables-persistent