---
- name: Ensure Certbot and certbot-dns-cloudflare is installed
  ansible.windows.win_command: pip install -U certbot certbot-dns-cloudflare

- name: Ensure that {{ certbot_dir }} directory exists
  ansible.windows.win_file:
    path: "{{ certbot_dir }}/repo"
    state: directory

- name: Check if git repo exists
  ansible.windows.win_stat:
    path: "{{ certbot_dir }}/repo/.git"
  register: repo_stats

- name: Clone Certbot repo
  ansible.windows.win_command: >
    "C:\Program Files\Git\bin\git.exe"
    "clone"
    "{{ certbot_repo }}"
    "{{ certbot_dir }}/repo"
    "--branch"
    "{{ certbot_version }}"
    "--recursive"
  args:
    creates: "{{ certbot_dir }}/repo/.git"
  when: not repo_stats.stat.exists

- name: Pull Certbot repo changes
  ansible.windows.win_command: >
    "C:\Program Files\Git\bin\git.exe"
    "pull"
  args:
    chdir: "{{ certbot_dir }}/repo"
  register: pull_repo_status
  when: repo_stats.stat.exists
  changed_when: not (pull_repo_status.rc ==0 and pull_repo_status.stdout | trim == "Already up to date.")

- name: Generate Let's Encrypt certificates
  include_tasks: certificate-Windows.yml
  loop: "{{ certbot_certs }}"
  loop_control:
    loop_var: certificate
  when:
    - certbot_create_if_missing
    - certbot_create_method == 'standalone'

- name: Check if the Scheduled Task to renew certs is registered
  community.windows.win_scheduled_task_stat:
    name: Certbot Renew Task
  register: task_stat

# @action Ensures Certificates are renewed
# Sets up Scheduled Task to renew Let's Encrypt Certificates on Windows Systems
- name: Create a task to renew Let's Encrypt Certs
  ansible.windows.win_command: powershell.exe -NoProfile -NonInteractive -File renew-up.ps1
  args:
    chdir: "{{ certbot_dir }}/repo/windows-installer/assets"
  when: not task_stat.task_exists
