---
- name: Install step
  apt:
    deb: https://github.com/smallstep/cli/releases/download/v0.21.0/step-cli_0.21.0_amd64.deb

- name: Install step-ca
  apt:
    deb: https://github.com/smallstep/certificates/releases/download/v0.21.0/step-ca_0.21.0_amd64.deb

- name: Enable and start step-ca service
  block:
    - name: Copy step-ca service file
      copy:
        src: step-ca.service
        dest: /etc/systemd/system/step-ca.service

    - name:
      systemd:
        name: step-ca.service
        daemon-reload: yes
        enabled: yes
        state: started
      register: stepca_status
      ignore_errors: yes

- name: Configure step-ca
  block:
    - name: Install pexpect
      apt:
        name: python3-pexpect
        state: present

    - name: Copy password file
      template:
        src: step_password.jinja
        dest: /root/step_password
        mode: "0400"

    - name: Init CA
      shell:
        cmd: "step ca init --name={{ inventory_hostname }} --dns={{ inventory_hostname }} --address=0.0.0.0:9443 --provisioner=bbohard@cadoles.com --password-file=/root/step_password"
      register: init_result

    - name: Remove pexpect
      apt:
        name: python3-pexpect
        state: absent

    - name:
      systemd:
        name: step-ca.service
        enabled: yes
        state: started
  when: stepca_status.status.SubState == 'dead'

- name: Wait for valid status
  wait_for:
    port: 9443
    host: "{{ inventory_hostname }}"
    delay: 1
    timeout: 30
  delegate_to: localhost

- name: Create acme provisioner
  shell:
    cmd: step ca provisioner add acme --type ACME
  ignore_errors: yes

- name: Restart step-ca
  systemd:
    name: step-ca
    state: restarted
- name: Fetch root certificate
  fetch:
    dest: "fetched"
    src: "/root/.step/certs/root_ca.crt"

- name: Fetch intermediate certificate
  fetch:
    dest: "fetched"
    src: "/root/.step/certs/intermediate_ca.crt"
