---
# Flip the chemnitz domains (countdown_domains) from the static countdown page
# to the live staging app, then validate + reload Caddy.
#
#   ansible-playbook playbooks/switch-to-staging.yml -i inventory/test.yml --ask-vault-pass
#
# Re-runnable and idempotent — run it to go live, or to dry-run the cutover.
# To revert to the countdown page:
#   ansible-playbook playbooks/switch-to-staging.yml -i inventory/test.yml --ask-vault-pass -e chemnitz_live=false
- name: Switch chemnitz domains between countdown and the staging app
  hosts: all
  become: true

  vars:
    chemnitz_live: true

  tasks:
    - name: Fail early if the chemnitz domains are not configured
      ansible.builtin.assert:
        that:
          - countdown_domains is defined
          - countdown_domains | length > 0
        fail_msg: "countdown_domains must be set in the inventory before switching."

    - name: Render Caddyfile ({{ 'staging app' if chemnitz_live | bool else 'countdown page' }})
      ansible.builtin.template:
        src: "{{ playbook_dir }}/../roles/caddy/templates/Caddyfile.j2"
        dest: /etc/caddy/Caddyfile
        mode: "0644"
      register: caddyfile_result

    - name: Validate Caddyfile
      ansible.builtin.command: caddy validate --adapter caddyfile --config /etc/caddy/Caddyfile
      changed_when: false

    - name: Reload Caddy
      ansible.builtin.systemd:
        name: caddy
        state: reloaded
      when: caddyfile_result is changed

    - name: Report active mode
      ansible.builtin.debug:
        msg: >-
          chemnitz domains now serving
          {{ 'the staging app (port ' ~ (countdown_live_port | default(3001)) ~ ')'
             if chemnitz_live | bool else 'the countdown page' }}.
