---
- name: Install nginx
  ansible.builtin.apt:
    pkg:
      - nginx
    update_cache: true
  become: true

- name: Clone acme.sh github
  ansible.builtin.git:
    repo: https://github.com/acmesh-official/acme.sh.git
    dest: /home/ansible/acme
    depth: 1
    update: false
    version: master

- name: Install acme.sh
  ansible.builtin.command: >-
    ./acme.sh --install --log
    --days 30
    {{ "--accountemail " + nginx_acme_sh_account_email if nginx_acme_sh_account_email else "" }}
  args:
    chdir: "/home/ansible/acme"
    creates: "~/.acme.sh/acme.sh"
  become: true

- name: Determine if acme.sh is installed
  ansible.builtin.stat:
    path: "~/.acme.sh/acme.sh"
  register: is_acme_sh_installed
  become: true

- name: Upgrade acme.sh
  ansible.builtin.command: ./acme.sh --upgrade
  args:
    chdir: "~/.acme.sh"
  when:
    - is_acme_sh_installed.stat.exists
  register: upgrade_result
  changed_when: upgrade_result.rc == 0 and "Upgrade success" in upgrade_result.stdout
  become: true

- name: Create cert path
  ansible.builtin.file:
    state: directory
    path: /etc/nginx/acme.sh/
    mode: "0700"
    owner: root
    group: root
  become: true

- name: Set default CA to letsencrypt
  ansible.builtin.command: >-
    ./acme.sh --set-default-ca --server letsencrypt
  args:
    chdir: "~/.acme.sh"
  become: true
  changed_when: false

- name: Issue acme.sh certificate(s) (this will sleep for dns_sleep seconds)
  ansible.builtin.command: >-
    ./acme.sh --issue -d {{ nginx_acme_sh_domains | join(" -d ") }}
    --dns dns_cf
  args:
    chdir: "~/.acme.sh"
  environment:
    CF_Token: "{{ nginx_cloudflare_api_key }}"
    CF_Email: "{{ nginx_acme_sh_account_email }}"
  become: true
  register: issue_result
  changed_when: issue_result.rc == 0 and "Cert success" in issue_result.stdout
  failed_when: issue_result.rc != 0 and "Domains not changed" not in issue_result.stdout

- name: Install certs to nginx
  ansible.builtin.command: >-
    ./acme.sh --install-cert -d {{ nginx_acme_sh_domains[0] }}
    --key-file       /etc/nginx/acme.sh/{{ item }}.key.pem
    --fullchain-file /etc/nginx/acme.sh/{{ item }}.cert.pem
    --reloadcmd     "systemctl reload nginx"
  become: true
  loop: "{{ nginx_acme_sh_domains }}"
  args:
    chdir: "~/.acme.sh"
  register: install_result
  changed_when: install_result.rc == 0 and "Reload successful" in install_result.stdout
  failed_when: install_result.rc != 0
