---
# Playbook 06: Configure Caddy
# Setup reverse proxy and obtain SSL certificates

- name: Configure Caddy Reverse Proxy
  hosts: all
  become: yes
  
  tasks:
    - name: Validate Caddyfile syntax
      command: docker exec caddy caddy validate --config /etc/caddy/Caddyfile
      args:
        chdir: "{{ deployment_dir }}"
      register: caddy_validate
      failed_when: caddy_validate.rc != 0
      changed_when: false

    - name: Reload Caddy configuration
      command: docker exec caddy caddy reload --config /etc/caddy/Caddyfile
      args:
        chdir: "{{ deployment_dir }}"

    - name: Wait for SSL certificates (may take 1-2 minutes)
      pause:
        seconds: 30
        prompt: "Waiting for Let's Encrypt to issue certificates..."

    - name: Test HTTPS endpoint for Nextcloud
      uri:
        url: "https://{{ subdomain_nextcloud }}.{{ domain }}/status.php"
        validate_certs: yes
        status_code: 200
      register: https_test
      until: https_test.status == 200
      retries: 10
      delay: 10
      ignore_errors: yes

    - name: Display Caddy status
      debug:
        msg: |
          ✓ Caddyfile validated
          ✓ Caddy reloaded
          {% if https_test.status == 200 %}
          ✓ HTTPS working: https://{{ subdomain_nextcloud }}.{{ domain }}
          {% else %}
          ⚠ HTTPS check failed - verify DNS and firewall
          {% endif %}
