---
# file: roles/haproxy/tasks/letsencrypt.yml

- name: "[letsencrypt] reload haproxy immediately when the configuration has changed, else letsencrypt challenge may fail"
  systemd:
    name: haproxy
    state: reloaded
  when: haproxy_config.changed

- name: "[letsencrypt] install git curl hexdump"
  apt:
    name:
      - git
      - curl
      - bsdmainutils
    update_cache: yes

- name: "[letsencrypt] directory /usr/local/etc/letsencrypt"
  file:
    path: "{{ item }}"
    state: directory
  loop:
    - "/usr/local/etc/letsencrypt"
    - "/var/www/letsencrypt"

- name: "[letsencrypt] git repo dehydrated"
  git:
    repo: https://github.com/dehydrated-io/dehydrated
    dest: /usr/local/etc/letsencrypt/dehydrated
    clone: yes

- name: "[letsencrypt] domains.txt"
  template:
    src: letsencrypt_domains.txt
    dest: /usr/local/etc/letsencrypt/dehydrated/domains.txt
    backup: yes
  when: haproxy_https_monitoring is defined

- name: "[letsencrypt] le.config"
  template:
    src: letsencrypt_le.config
    dest: /usr/local/etc/letsencrypt/dehydrated/le.config
    backup: yes

- name: "[letsencrypt] dehydrated_haproxy_hook.sh"
  copy:
    src: "dehydrated_haproxy_hook.sh"
    dest: "/usr/local/etc/letsencrypt/dehydrated_haproxy_hook.sh"
    mode: 0700
    backup: yes

- name: "[letsencrypt] http-letsencrypt.service"
  copy:
    src: "http-letsencrypt.service"
    dest: "/etc/systemd/system/http-letsencrypt.service"

- name: "[letsencrypt] make sure the letsencrypt terms are accepted"
  command: /usr/local/etc/letsencrypt/dehydrated/dehydrated --register --accept-terms --config /usr/local/etc/letsencrypt/dehydrated/le.config
  register: accept_terms
  changed_when: "accept_terms.stdout != '# INFO: Using main config file /usr/local/etc/letsencrypt/dehydrated/le.config\n+ Account already registered!'"

- name: "[letsencrypt] generate certificate(s) if needed"
  command: "/usr/local/etc/letsencrypt/dehydrated/dehydrated --cron --out /usr/local/etc/tls --challenge http-01 --config /usr/local/etc/letsencrypt/dehydrated/le.config --hook /usr/local/etc/letsencrypt/dehydrated_haproxy_hook.sh"
  register: generate_certificates
  changed_when: "'Generating private key' in generate_certificates.stdout"

- name: "[letsencrypt] dehydrated crontab for automatic renew"
  cron:
    name: dehydrated
    minute: "{{ 59 | random(seed=inventory_hostname) }}"
    hour: "{{ 23 | random(seed=inventory_hostname) }}"
    job: "/usr/local/etc/letsencrypt/dehydrated/dehydrated --cron --keep-going --out /usr/local/etc/tls --challenge http-01 --config /usr/local/etc/letsencrypt/dehydrated/le.config --hook /usr/local/etc/letsencrypt/dehydrated_haproxy_hook.sh"
