---

- name: Assert
  assert:
    that: ansible_os_family == 'Debian'

- name: apt install TLS CA certs
  apt:
    name: '{{ item }}'
    state: present
    update_cache: yes
    cache_valid_time: 3600
  with_items:
  - ssl-cert
  - ca-certificates

- name: Set TLS key and certificate
  set_fact:
    tls_key_path: '/etc/ssl/private/{{ tls_key|default("ssl-cert-snakeoil")|basename }}.key'
    tls_cert_path: '/etc/ssl/certs/{{ tls_cert|default("ssl-cert-snakeoil")|basename }}.pem'
    tls_ca_cert_path: '/etc/ssl/certs/{{ tls_ca_cert|default(tls_cert|default("ssl-cert-snakeoil"))|basename }}.pem'

- name: Copy TLS certificate and key
  when: tls_cert is defined and tls_key is defined and tls_ca_cert is defined
  copy:
    src: '{{ item.src }}'
    dest: '{{ item.dest }}'
    owner: root
    group: '{{ item.group }}'
    mode: '{{ item.mode }}'
  register: tls_copy
  with_items:
    - src: '{{ tls_key }}'
      dest: '{{ tls_key_path }}'
      mode: 0o0640
      group: ssl-cert
    - src: '{{ tls_cert }}'
      dest: '/usr/local/share/ca-certificates/{{ tls_cert|basename }}.crt'
      mode: 0o0644
      group: root
    - src: '{{ tls_ca_cert }}'
      dest: '/usr/local/share/ca-certificates/{{ tls_ca_cert|basename }}.crt'
      mode: 0o0644
      group: root

- name: Update certificate authority store
  command: /usr/sbin/update-ca-certificates
  when: tls_copy.changed
