---
- name: allow http from vpn
  ufw:
    rule: allow
    port: '80'
    proto: tcp
    from: 100.64.0.0/10

- name: allow https from vpn
  ufw:
    rule: allow
    port: '443'
    proto: tcp
    from: 100.64.0.0/10

- name: restart ufw
  service: name=ufw state=restarted enabled=yes

- name: install letsencrypt
  apt: name=letsencrypt state=latest

- name: create letsencrypt directory
  file: name=/var/www/letsencrypt state=directory

- name: install nginx
  apt: name=nginx state=latest

- name: remove default nginx
  file: name=/etc/nginx/sites-enabled/default state=absent

- name: generate dhparams
  shell: openssl dhparam -out /etc/nginx/dhparams.pem 2048
  args:
    creates: /etc/nginx/dhparams.pem

- name: add system nginx config
  template:
    src: ../files/nginx.conf
    dest: /etc/nginx/nginx.conf

- name: copy http nginx configuration for each domain
  copy:
    src: "{{ item }}"
    dest: "/etc/nginx/sites-enabled/"
  with_fileglob:
    - "files/{{ inventory_hostname }}/http.*.conf"

- name: restart nginx to get letsencrypt certificate
  service: name=nginx state=restarted enabled=yes

- name: find deployed domains
  ansible.builtin.find:
    paths: "/etc/nginx/sites-enabled/"
    patterns: "http.*.conf"
  register: nginx_conf_files
  delegate_to: "{{ inventory_hostname }}"

- name: extract domains from deployed nginx configurations
  shell: |
    grep -oP 'server_name\s+\K[^;]+' "{{ item.path }}"
  loop: "{{ nginx_conf_files.files }}"
  register: extracted_domains

# crt is given from the "ca" role to all hosts; that needs to run first
- name: request letsencrypt certificate
  shell: >
    REQUESTS_CA_BUNDLE="/usr/local/share/ca-certificates/{{ step_bootstrap_ca_url }}.crt" \
      letsencrypt certonly -n -d {{ item.stdout }} \
      --server https://{{ step_bootstrap_ca_url }}:{{ step_ca_port }}/acme/ACME/directory \
      --webroot -w /var/www/letsencrypt \
      --agree-tos --email {{ step_acme_cert_contact }}
  args:
    creates: "/etc/letsencrypt/live/{{ item.stdout }}"
  loop: "{{ extracted_domains.results }}"
  when: item.stdout != ""

- name: copy https nginx configuration for each domain
  copy:
    src: "{{ item }}"
    dest: "/etc/nginx/sites-enabled/"
  with_fileglob:
    - "files/{{ inventory_hostname }}/https.*.conf"

- name: reload nginx to activate sites
  service: name=nginx state=restarted

- name: add daily renewal
  cron:
    name: "letsencrypt_renewal"
    special_time: "daily"
    job: "REQUESTS_CA_BUNDLE=/usr/local/share/ca-certificates/{{ step_bootstrap_ca_url }}.crt letsencrypt renew --force-renewal"