---
- name: Set common facts
  ansible.builtin.import_tasks: tasks/set-default-facts.yml

- name: Deploy {{ role_name }}
  vars:
    env: "{{ lego_env }}"
    json: "{{ vault_acmedns_registered | acmedns_to_lego }}"
    compose: "{{ lego_compose }}"
  block:
    - name: Import prepare tasks for common service
      ansible.builtin.import_tasks: tasks/prepare-common-service.yml

    - name: Create _certificates directory
      ansible.builtin.file:
        path: "{{ certificates_path }}"
        state: directory
        mode: "0755"

    - name: Import tasks specific to the config directory
      ansible.builtin.import_tasks: config.yml
    - name: Import tasks specific to hooks
      ansible.builtin.import_tasks: hooks.yml
    - name: Import tasks specific to systemd
      ansible.builtin.import_tasks: systemd.yml

    - name: Copy the run script
      ansible.builtin.copy:
        src: "lego.sh"
        dest: "{{ (service_path, 'lego.sh') | path_join }}"
        mode: "0755"

    - name: Import tasks create a service.env file
      ansible.builtin.import_tasks: tasks/steps/template-service-env.yml

    - name: Run certificate-script for domains
      ansible.builtin.command:
        cmd: "./lego.sh {{ item }}"
        chdir: "{{ service_path }}"
      become: true
      loop: "{{ lego_host_certificates }}"
      register: cmd_result
      changed_when: cmd_result.stderr | regex_search('Server responded with a certificate.')