- name: Install and Configure Caddy
  block:
    - name: Download xcaddy GPG key
      ansible.builtin.get_url:
        url: https://dl.cloudsmith.io/public/caddy/xcaddy/gpg.key
        dest: /usr/share/keyrings/caddy-xcaddy-archive-keyring.gpg
        mode: "0644"

    - name: Fetch xcaddy APT repository definition
      ansible.builtin.get_url:
        url: https://dl.cloudsmith.io/public/caddy/xcaddy/debian.deb.txt
        dest: /tmp/caddy-xcaddy.list.tmp
        mode: "0644"
      register: caddy_xcaddy_repo_url_content

    - name: Add xcaddy APT repository file
      ansible.builtin.copy:
        src: /tmp/caddy-xcaddy.list.tmp
        dest: /etc/apt/sources.list.d/caddy-xcaddy.list
        owner: root
        group: root
        mode: "0644"
        remote_src: true

    - name: Update apt cache after adding xcaddy repository
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 0

    - name: Install xcaddy
      ansible.builtin.apt:
        name: xcaddy
        state: present

    - name: Build Caddy with custom modules
      ansible.builtin.command: |
        xcaddy build \
          --with github.com/mholt/caddy-l4 \
          --with github.com/mholt/caddy-webdav \
          --output /usr/local/bin/caddy
      args:
        creates: /usr/local/bin/caddy
      register: caddy_build_result

    - name: Create Caddy group
      ansible.builtin.group:
        name: caddy
        system: true
        state: present

    - name: Create Caddy user
      ansible.builtin.user:
        name: caddy
        group: caddy
        groups: www-data
        append: true
        system: true
        create_home: true
        home: /var/lib/caddy
        shell: /usr/sbin/nologin
        comment: Caddy web server
        state: present
      notify: Restart caddy

    - name: Create Caddy config and sites directories
      ansible.builtin.file:
        path: "{{ item }}"
        state: directory
        owner: root
        group: root
        mode: "0755"
      loop: [/etc/caddy, /etc/caddy/sites]

    - name: Create Caddy log directory
      ansible.builtin.file:
        path: /var/log/caddy
        state: directory
        owner: caddy
        group: caddy
        mode: "0755"

    - name: Deploy Caddy systemd service file
      ansible.builtin.copy:
        src: files/caddy.service
        dest: /etc/systemd/system/caddy.service
        owner: root
        group: root
        mode: "0644"

    - name: Copy Caddyfile from local path to /etc/caddy/Caddyfile
      ansible.builtin.copy:
        src: files/Caddyfile
        dest: /etc/caddy/Caddyfile
        owner: root
        group: root
        mode: "0644"
      notify: Restart caddy

    - name: Enable and start Caddy service
      ansible.builtin.systemd_service:
        name: caddy
        enabled: true
        state: started
        daemon_reload: true
