---

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

- name: Create TLS key-owner group
  group:
    name: ssl-cert
    state: present

- name: Create TLS keys and certs directories
  with_items:
  - name: certs
    mode: 0o0755
    group: wheel
  - name: private
    mode: 0o0750
    group: ssl-cert
  file:
    path: '/etc/ssl/{{ item.name }}'
    owner: root
    group: '{{ item.group }}'
    mode: '{{ item.mode }}'
    state: directory

- name: Get current CA store
  get_url:
    url: http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/lib/libcrypto/cert.pem
    dest: /etc/ssl/certs/ca-certificates.pem
    owner: root
    group: wheel
    mode: 0o0644

- name: Copy update-ca-certifcates script
  copy:
    src: update-ca-certificates
    dest: /usr/local/sbin/update-ca-certificates
    owner: root
    group: wheel
    mode: 0o0755

- stat:
    path: /etc/ssl/private/ssl-cert-snakeoil.key
  register: tls_stat_key

- name: Generate self-signed TLS key
  when: not tls_stat_key.stat.exists
  command: /usr/bin/openssl genrsa -out /etc/ssl/private/ssl-cert-snakeoil.key 2048

- stat:
    path: /etc/ssl/certs/ssl-cert-snakeoil.pem
  register: tls_stat_cert

- name: Generate self-signed TLS cert
  when: not tls_stat_cert.stat.exists
  command: |
    /usr/bin/openssl req \
        -x509 \
        -new \
        -key /etc/ssl/private/ssl-cert-snakeoil.key \
        -nodes \
        -out /etc/ssl/certs/ssl-cert-snakeoil.pem \
        -days 3650
        -subj "/CN={{ ansible_fqdn }}"

- 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
  with_items:
    - src: '{{ tls_key }}'
      dest: '{{ tls_key_path }}'
    - src: '{{ tls_cert }}'
      dest: '{{ tls_cert_path }}'
    - src: '{{ tls_ca_cert }}'
      dest: '{{ tls_ca_cert_path }}'
  copy:
    src: '{{ item.src }}'
    dest: '{{ item.dest }}'
    owner: root
    group: wheel
    mode: 0o0644
  register: tls_copy

- name: Update certificate authority store
  when: tls_copy.changed or not tls_stat_cert.stat.exists
  command: /usr/local/sbin/update-ca-certificates
