---
- name: Delete the lock files
  file:
    dest: "{{ config_prefix|default('/') }}etc/wireguard/private_{{ item }}.lock"
    state: absent
  when: keys_clean_all|bool
  with_items:
    - "{{ users }}"
    - "{{ IP_subject_alt_name }}"

- name: Generate private keys
  command: wg genkey
  register: wg_genkey
  args:
    creates: "{{ config_prefix|default('/') }}etc/wireguard/private_{{ item }}.lock"
  with_items:
    - "{{ users }}"
    - "{{ IP_subject_alt_name }}"

- block:
  - name: Save private keys
    copy:
      dest: "{{ wireguard_pki_path }}/private/{{ item['item'] }}"
      content: "{{ item['stdout'] }}"
      mode: "0600"
    no_log: "{{ no_log|bool }}"
    when: item.changed
    with_items: "{{ wg_genkey['results'] }}"
    delegate_to: localhost
    become: false

  - name: Touch the lock file
    file:
      dest: "{{ config_prefix|default('/') }}etc/wireguard/private_{{ item }}.lock"
      state: touch
    with_items:
      - "{{ users }}"
      - "{{ IP_subject_alt_name }}"
  when: wg_genkey.changed

- name: Delete the preshared lock files
  file:
    dest: "{{ config_prefix|default('/') }}etc/wireguard/preshared_{{ item }}.lock"
    state: absent
  when: keys_clean_all|bool
  with_items:
    - "{{ users }}"
    - "{{ IP_subject_alt_name }}"

- name: Generate preshared keys
  command: wg genpsk
  register: wg_genpsk
  args:
    creates: "{{ config_prefix|default('/') }}etc/wireguard/preshared_{{ item }}.lock"
  with_items:
    - "{{ users }}"
    - "{{ IP_subject_alt_name }}"

- block:
  - name: Save preshared keys
    copy:
      dest: "{{ wireguard_pki_path }}/preshared/{{ item['item'] }}"
      content: "{{ item['stdout'] }}"
      mode: "0600"
    no_log: "{{ no_log|bool }}"
    when: item.changed
    with_items: "{{ wg_genpsk['results'] }}"
    delegate_to: localhost
    become: false

  - name: Touch the preshared lock file
    file:
      dest: "{{ config_prefix|default('/') }}etc/wireguard/preshared_{{ item }}.lock"
      state: touch
    with_items:
      - "{{ users }}"
      - "{{ IP_subject_alt_name }}"
  when: wg_genpsk.changed

- name: Generate public keys
  shell: |
    set -o pipefail
    echo "{{ lookup('file', wireguard_pki_path + '/private/' + item) }}" |
    wg pubkey
  register: wg_pubkey
  changed_when: false
  args:
    executable: bash
  with_items:
    - "{{ users }}"
    - "{{ IP_subject_alt_name }}"

- name: Save public keys
  copy:
    dest: "{{ wireguard_pki_path }}/public/{{ item['item'] }}"
    content: "{{ item['stdout'] }}"
    mode: "0600"
  no_log: "{{ no_log|bool }}"
  with_items: "{{ wg_pubkey['results'] }}"
  delegate_to: localhost
  become: false
