# This playbook is inspired by
# https://mikeshultz.com/setting-up-lets-encrypt-with-lighttpd-and-certbot.html
# Particularly it follows "(Option B) The Hard Way"

- name: Install required packages
  dnf: state=latest name={{ item }}
  with_items:
    - certbot

- name: Create The Web Root
  file:
    path: /var/certbot/public_html/.well-known/
    state: directory
    owner: lighttpd
    group: lighttpd
    mode: g+s

- name: Check that cert file exists
  stat:
    path: "/etc/letsencrypt/live/copr-be-dev.cloud.fedoraproject.org/cert.pem"
  register: stat_cert

# This is only for initial setup
# In such case, lighttpd config expects certificate files in /etc/letsencrypt/live,
# but it doesn't exist yet and therefore lighttpd refuses to start at all.
# We will use certbot standalone server to get certificates and then let the playbook to
# parse them and start the lighttpd again.
# Once we have at least some existing certificate files, this step will be skipped.
- name: Should admin run certbot?
  fail:
    msg:
      - "There are no certificates yet"
      - "Please temporarily stop lighttpd and run:"
      - "  certbot certonly --standalone --manual-public-ip-logging-ok -d copr-be-dev.cloud.fedoraproject.org"
      - "Let it stopped and re-run the playbook."
  when:
    - stat_cert.stat.exists == False

- name: Reformat Cert Files For Lighttpd
  shell: cat /etc/letsencrypt/live/copr-be-dev.cloud.fedoraproject.org/privkey.pem /etc/letsencrypt/live/copr-be-dev.cloud.fedoraproject.org/cert.pem > /etc/letsencrypt/live/copr-be-dev.cloud.fedoraproject.org/combined.pem

- name: Give Lighty Permissions
  file:
    path: "{{ item }}"
    group: lighttpd
    mode: g+x
  with_items:
    - /etc/letsencrypt
    - /etc/letsencrypt/live

- name: Service lighttpd should be running
  service:
    name: lighttpd
    state: started

- name: Automate Renewal
  cron:
    name: "Get fresh letsencrypt certificates"
    special_time: daily
    job: "certbot certonly --force-renew --webroot -w /var/certbot/public_html -d copr-be-dev.cloud.fedoraproject.org"
