---
- name: Restart gpg-agent
  become: true
  shell: "gpgconf --kill all"

- name: Ensure .gnupg config directory exists with right permissions
  become: true
  file: dest={{ gpg_home }}/.gnupg state=directory mode=0700 owner="{{ rootUser }}"

## Note: matching on realname or email doesn't allow to create multiple keys. alternative?
- name: check existing secret key
  shell: "gpg --list-secret-keys | grep '{{ gpg_realname }}'"
  changed_when: false
  ignore_errors: true
  become: yes
  become_user: "{{ rootUser }}"
  register: gpgkeys
  
- name: Check expired keys
  become: yes
  shell: "gpg2 --list-keys {{ gpg_realname }} | grep 'expired'"
  ignore_errors: yes
  failed_when: false
  register: gpgExpKeys
  when:  gpgkeys.stdout_lines|length > 0

- name: Update expired
  become: yes
  shell: 'printf "expire\n{{ gpg_expire }}\nsave\n" | gpg --batch --command-fd 0 --status-fd=2 --edit-key {{ gpg_realname }}'
  when: gpgkeys.stdout_lines|length > 0 and gpgExpKeys.stdout_lines|length > 0

- include: gpg-gen-key.yaml
  when: gpgkeys.stdout_lines|length < 1

- name: get user armored public key
  become: true
  shell: "sudo gpg --armor --output {{ gpg_pubkeyfileexport }} --export {{ gpg_useremail }}"
  when: gpgkeys.stdout_lines|length < 1 or (gpgkeys.stdout_lines|length > 0 and gpgExpKeys.stdout_lines|length > 0)

- name: After export move the key to /var/packages
  become: true
  shell: "sudo mv {{ gpg_pubkeyfileexport }} /var/packages"
  when: gpgkeys.stdout_lines|length < 1 or (gpgkeys.stdout_lines|length > 0 and gpgExpKeys.stdout_lines|length > 0)
