---
- name: Obtain Let's Encrypt SSL certificate using ClouDNS
  hosts: certbot
  become: true

  tasks:
    - name: Set required facts
      ansible.builtin.set_fact:
        cloudns_credentials_path: "/etc/letsencrypt/cloudns.ini"

    - name: Check if cloudDNS credentials are set or fail
      when: not (cloudns_auth_id is defined and cloudns_auth_password is defined)
      ansible.builtin.fail:
        msg: "CloudDNS credentials are not set"

    - name: Check if cloudDNS nameserver is set or fail
      when: not (cloudns_nameserver is defined)
      ansible.builtin.fail:
        msg: "CloudDNS nameserver is not set"

    - name: Install Certbot and dependencies
      when: ansible_os_family == "RedHat"
      ansible.builtin.dnf:
        name:
          - certbot
        state: present

    - name: Install cloudDNS plugin dependencies
      ansible.builtin.pip:
        name:
          - certbot-dns-cloudns
        state: present

    - name: Create ClouDNS credentials file
      ansible.builtin.copy:
        dest: "{{ cloudns_credentials_path }}"
        content: |
          dns_cloudns_auth_id={{ cloudns_auth_id }}
          dns_cloudns_auth_password={{ cloudns_auth_password }}
        owner: root
        group: root
        mode: '0600'

    - name: Obtain SSL certificate using Certbot with ClouDNS plugin
      ansible.builtin.command: >
        certbot certonly --authenticator dns-cloudns
          --non-interactive
          --agree-tos
          --email {{ certbot_email }}
          --dns-cloudns-credentials {{ cloudns_credentials_path }}
          --dns-cloudns-nameserver {{ cloudns_nameserver }} -d {{ item }}
      args:
        creates: "/etc/letsencrypt/live/{{ item }}/fullchain.pem"
      loop: "{{ certbot_domains }}"

    - name: Set up automatic certificate renewal
      ansible.builtin.cron:
        name: "Renew Let's Encrypt certificates"
        job: "certbot renew --quiet"
        minute: 0
        hour: 3
