---
- name: copy binaries
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dst }}"
    owner: root
    group: root
    mode: '0755'
    backup: yes
  with_items:
    - { src: "files/step/step_0.15.16/{{ ansible_architecture }}/bin/step", dst: "/bin/step" }
    - { src: "files/step-ca/step-ca_0.15.15/{{ ansible_architecture }}/bin/step-ca", dst: "/bin/step-ca" }

- name: create user for step-ca
  user:
    name: step
    state: present
    shell: /bin/false
    system: yes
    createhome: yes
    home: /etc/step-ca

- name: generate /etc/step-ca/password.txt
  template:
    src: password.txt.j2
    dest: /etc/step-ca/password.txt
    owner: step
    group: step
    mode: "0770"

- name: set permissions correct
  file:
    dest: /etc/step-ca
    owner: step
    group: step
    mode: "0770"
    recurse: yes

- name: init step-ca
  command: sudo -u step step ca init -ssh --name="{{ pki_name }}" --dns {{ ansible_hostname }} --issuer="{{ pki_name }}" --address=:4343 --provisioner="{{ pki_name }}" --password-file=/etc/step-ca/password.txt --provisioner-password-file=/etc/step-ca/password.txt
  args:
    creates: /etc/step-ca/.step/config

- name: correct badgerValueLogLoadingMode
  lineinfile:
    path: /etc/step-ca/.step/config/ca.json
    line: "{{'\t'}}{{'\t'}},\"badgerValueLogLoadingMode\": \"FileIO\""
    state: present
    insertafter: "{{'\t'}}{{'\t'}}\"badgerFileLoadingMode\": \"\""
  notify:
    - restart step-ca

- name: generate /etc/systemd/system/step-ca.service
  template:
    src: step-ca.service.j2
    dest: /etc/systemd/system/step-ca.service
    owner: root
    group: root
    mode: "0644"
  notify:
    - reload systemd

- name: Flush handlers
  meta: flush_handlers

- name: enable step-ca
  systemd:
    name: step-ca
    enabled: yes
    masked: no
  notify:
    restart step-ca

- name: Flush handlers
  meta: flush_handlers

- name: check for acme privisioner
  lineinfile:
    path: /etc/step-ca/.step/config/ca.json
    regexp: '.*"type": "ACME",.*'
    line: "{{'\t'}}{{'\t'}}{{'\t'}}{{'\t'}}\"type\": \"ACME\","
    state: present
  check_mode: yes
  register: acmepresent

- name: add acme provisioner
  command: sudo -u step step ca provisioner add acme --type ACME
  when: acmepresent is changed
  notify:
    - restart step-ca

- name: check for default JWK privisioner
  lineinfile:
    path: /etc/step-ca/.step/config/ca.json
    regexp: '.*"type": "JWK",.*'
    line: "{{'\t'}}{{'\t'}}{{'\t'}}{{'\t'}}\"type\": \"JWK\","
    state: absent
  check_mode: yes
  register: jwkabsent

- name: remove jwk provisioner
  command: sudo -u step step ca provisioner remove "{{ pki_name }}" --type JWK
  when: jwkabsent is changed
  notify:
    - restart step-ca