---
# file: roles/letsencrypt/tasks/cert_generate.yml

- block:

  - name: Stop services
    service:
      name: '{{ item }}'
      state: stopped
    with_items: '{{ letsencrypt_pause_services|default([]) }}'

  - name: Open Port
    iptables:
      chain: INPUT
      source: 0.0.0.0
      destination_port: 54321
      protocol: tcp
      jump: ACCEPT
      state: present
    #when: groups.proxyserver is defined and inventory_hostname in groups.proxyserver
    when: no

  - name: Install New Cert via webroot
    shell: certbot certonly --expand --non-interactive --config /etc/letsencrypt/{{ cert.domain }}.ini --cert-name {{ cert.domain }} --webroot-path /var/www/html --webroot
    when: groups.proxyserver is not defined or inventory_hostname not in groups.proxyserver

  - name: Install New Cert via HaProxy
    shell: certbot certonly --expand --non-interactive --config /etc/letsencrypt/{{ cert.domain }}.ini --http-01-port {{ port }} --preferred-challenges http-01 --cert-name {{ cert.domain }}
    when: groups.proxyserver is defined and inventory_hostname in groups.proxyserver

  - name: Close Port
    iptables:
      chain: INPUT
      source: 0.0.0.0
      destination_port: 54321
      protocol: tcp
      jump: ACCEPT
      state: absent
    #when: groups.proxyserver is defined and inventory_hostname in groups.proxyserver
    when: no

  - include_tasks: cert_deploy.yml

  - name: Start services
    service:
      name: '{{ item }}'
      state: started
    with_items: '{{ letsencrypt_pause_services|default([]) }}'
    ignore_errors: yes

  tags:
    - ApacheConfig
    - Certs
