---
#--------------------------------------------------------------#
# 1. Caddy Directory                               [caddy_dir]
#--------------------------------------------------------------#
- name: create caddy directory
  tags: caddy_dir
  file:
    path: "{{ item.path }}"
    state: "{{ item.state | default('directory') }}"
    owner: "{{ item.owner | default('root') }}"
    group: "{{ item.group | default('root') }}"
    mode:  "{{ item.mode | default('0755') }}"
  with_items:
    - { path: "/etc/caddy" }
    - { path: "/etc/caddy/conf.d" }

#--------------------------------------------------------------#
# 2. Caddy Config                               [caddy_config]
#--------------------------------------------------------------#
- name: create caddy config
  tags: caddy_config
  template:
    src: caddy/Caddyfile
    dest: /etc/caddy/conf.d/observability.caddy
    owner: root
    group: root
    mode: '0644'
  notify: reload caddy

- name: check existing caddy main config
  tags: caddy_config
  stat:
    path: /etc/caddy/Caddyfile
  register: caddy_main_config

- name: bootstrap caddy main config when missing
  tags: caddy_config
  copy:
    dest: /etc/caddy/Caddyfile
    owner: root
    group: root
    mode: '0644'
    content: |
      {
      }

      import /etc/caddy/conf.d/*.caddy
  when: not caddy_main_config.stat.exists
  notify: reload caddy

- name: ensure caddy main config imports conf.d snippets
  tags: caddy_config
  lineinfile:
    path: /etc/caddy/Caddyfile
    line: "import /etc/caddy/conf.d/*.caddy"
    insertafter: EOF
    state: present
  when: caddy_main_config.stat.exists
  notify: reload caddy

#--------------------------------------------------------------#
# 3. Caddy Service                              [caddy_launch]
#--------------------------------------------------------------#
# If installed via script/binary, we might need a systemd service.
# If installed via yum/apt, it usually comes with one.
# Assuming we need to ensure it's enabled and started.
- name: launch caddy service
  tags: caddy_launch
  systemd:
    name: caddy
    state: started
    enabled: yes
    daemon_reload: yes
