---

- name: Deploy mock config
  template: src=mock/{{ item }}.j2 dest=/etc/mock/{{ item }}
  loop:
    - site-defaults.cfg
    - el7-x86_64.cfg
    - el8-x86_64.cfg
    - el9-x86_64.cfg
  tags: rpm

- name: Deploy rpmmacros
  template: src=rpmmacros.j2 dest={{ rpm_root_dir }}/.rpmmacros owner={{ rpm_user }} mode=600
  tags: rpm

- name: Deploy main configuration
  template: src=config.yml.j2 dest={{ rpm_root_dir }}/etc/config.yml
  notify: restart build-watcher
  tags: rpm

- name: Check if gpg key exists
  shell: gpg --list-options show-only-fpr-mbox --list-secret-keys | grep -q "{{ rpm_gpg_email }}"
  failed_when: False
  changed_when: False
  register: rpm_gpg_key_exists
  become_user: "{{ rpm_user }}"
  tags: rpm

- name: Flush handlers to set permissions on directories
  meta: flush_handlers
  tags: rpm

- when: rpm_gpg_key_exists.rc != 0
  block:
    - name: Generate main key
      shell: |
        gpg --batch \
          --passphrase '{{ rpm_gpg_pass is defined | ternary(rpm_gpg_pass, '') }}' \
          --pinentry-mode loopback \
          --quick-gen-key "{{ rpm_gpg_name }} <{{ rpm_gpg_email }}>" rsa3072 default never

    - name: Get key ID
      shell: gpg --list-options show-only-fpr-mbox --list-secret-keys | grep {{ rpm_gpg_email }} | awk '{ print $1 }'
      register: rpm_gpg_key_id
      changed_when: False

    - name: Add sub key
      shell: |
        gpg --batch \
          --passphrase '{{ rpm_gpg_pass is defined | ternary(rpm_gpg_pass, '') }}' \
          --pinentry-mode loopback \
          --quick-add-key {{ rpm_gpg_key_id.stdout }} rsa3072 default never \

    - name: Export public key
      shell: gpg --export -a "rpms@lapiole.org" > {{ rpm_root_dir }}/repo/RPM-GPG-KEY

  become_user: "{{ rpm_user }}"
  tags: rpm

