---

- name: prepare local storage directory
  hosts: 127.0.0.1
  tasks:
    - name: create borg-keys directory
      file: path="{{ playbook_dir }}/../../borg-keys/" state=directory  # noqa 208

- name: fetch borg keys
  hosts: borg_clients
  tasks:
    - name: fetch borg key
      command: "/usr/local/bin/borg key export :: /dev/stdout"
      register: borg_key
      changed_when: "borg_key.rc == 0"

    - name: fetch borg offsite key
      command: "/usr/local/bin/borg-offsite key export :: /dev/stdout"
      register: borg_offsite_key
      changed_when: "borg_offsite_key.rc == 0"

    - name: save borg key
      shell: gpg --batch --armor --encrypt --output - >"{{ playbook_dir }}/../../borg-keys/{{ inventory_hostname }}.gpg" {% for userid in root_gpgkeys %}--recipient {{ userid }} {% endfor %}
      args:
        stdin: "{{ borg_key.stdout }}"
        chdir: "{{ playbook_dir }}/../.."
      delegate_to: localhost
      register: gpg_key
      changed_when: "gpg_key.rc == 0"

    - name: save borg offsite key
      shell: gpg --batch --armor --encrypt --output - >"{{ playbook_dir }}/../../borg-keys/{{ inventory_hostname }}-offsite.gpg" {% for userid in root_gpgkeys %}--recipient {{ userid }} {% endfor %}
      args:
        stdin: "{{ borg_offsite_key.stdout }}"
        chdir: "{{ playbook_dir }}/../.."
      delegate_to: localhost
      register: gpg_offsite_key
      changed_when: "gpg_offsite_key.rc == 0"
