---
- name: Install Caddy dependencies
  ansible.builtin.apt:
    name:
      - debian-keyring
      - debian-archive-keyring
      - apt-transport-https
      - curl
    state: present

- name: Add Caddy GPG key
  ansible.builtin.shell:
    cmd: curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key -o /etc/apt/keyrings/caddy-stable-archive-keyring.asc && chmod 644 /etc/apt/keyrings/caddy-stable-archive-keyring.asc
    creates: /etc/apt/keyrings/caddy-stable-archive-keyring.asc

- name: Add Caddy apt repository
  ansible.builtin.apt_repository:
    repo: "deb [signed-by=/etc/apt/keyrings/caddy-stable-archive-keyring.asc] https://dl.cloudsmith.io/public/caddy/stable/deb/ubuntu any-version main"
    state: present

- name: Install Caddy
  ansible.builtin.apt:
    name: caddy
    state: present
    update_cache: true

- name: Create countdown web root
  ansible.builtin.file:
    path: /var/www/countdown
    state: directory
    owner: caddy
    group: caddy
    mode: "0755"
  when: countdown_domains is defined and countdown_domains | length > 0

- name: Upload countdown page
  ansible.builtin.copy:
    src: "{{ playbook_dir }}/../../../countdown.html"
    dest: /var/www/countdown/index.html
    owner: caddy
    group: caddy
    mode: "0644"
  when: countdown_domains is defined and countdown_domains | length > 0

- name: Deploy Caddyfile
  ansible.builtin.template:
    src: Caddyfile.j2
    dest: /etc/caddy/Caddyfile
    mode: "0644"
  register: caddyfile_result

- name: Enable and start Caddy
  ansible.builtin.systemd:
    name: caddy
    enabled: true
    state: started

- name: Reload Caddy
  ansible.builtin.systemd:
    name: caddy
    state: reloaded