---

- name: Prepare Certbot
  hosts: localhost
  connection: local
  vars_files:
    - config.build.yaml
    - config.defaults.yaml
    - ../config.yaml

  tasks:
    - name: Prepare Python 3
      import_tasks: tasks_python.yaml

    - name: Check settings
      import_tasks: tasks_check_settings.yaml

    - name: Ensure Headwind Remote is not running
      docker_compose:
        project_src: ../
        state: absent
        remove_volumes: yes
      # test shell: docker-compose -f ./../docker-compose.yaml down --volumes

    - name: Process Nginx configuration for ACME challenge
      template:
        src: "{{ item }}"
        dest: ./dist/conf/nginx/{{ item | basename | regex_replace('\.j2$', '') }}
      with_fileglob:
        - ./templates/nginx-acme/*.j2

    - name: Start Nginx for ACME challenge
      docker_compose:
        project_src: ../
        services:
          - nginx
        state: present
      # test shell: docker-compose -f ./../docker-compose.yaml up --detach nginx

    - name: Run certbot
      shell: |
        case "{% if share_email %}true{% else %}false{% endif %}" in
          "true") eff_arg="--eff-email" ;;
          "false") eff_arg="--no-eff-email" ;;
        esac
        export PATH=$PATH:/usr/local/bin
        docker-compose -f ./../docker-compose.yaml run --rm --entrypoint "\
          certbot certonly -n --webroot -w /var/www/certbot \
            --email {{ email }} \
            $eff_arg
            -d {{ hostname }} \
            --rsa-key-size 4096 \
            --agree-tos" certbot

    - name: Stop services
      docker_compose:
        project_src: ../
        state: absent
        remove_volumes: yes
      # test shell: docker-compose -f ./../docker-compose.yaml down --volumes
