---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

- name: Include distribution specific variables
  include_vars: "{{ lookup('first_found', params) }}"
  vars:
    params:
      files:
        - "{{ ansible_facts.distribution }}.yml"
        - "{{ ansible_facts.os_family }}.yml"
        - default.yml
      paths:
        - "{{ role_path }}/vars"

- name: Install package
  action: "{{ ansible_facts.pkg_mgr }}"
  args:
    name: "{{ passwordstore_packages }}"
    state: present
  when: ansible_facts.pkg_mgr in ['apt', 'dnf', 'yum', 'pkgng', 'community.general.pkgng']

- block:
  # OpenSUSE Leap>=15.0 don't include password-store in main repo
  - name: SUSE | Add security:privacy repo
    template:
      src: security-privacy.repo.j2
      dest: /etc/zypp/repos.d/security:privacy.repo

  - name: SUSE | Install package
    package:
      name: password-store
      state: present
      update_cache: yes
      disable_gpg_check: yes
  when: ansible_facts.pkg_mgr in ['zypper', 'community.general.zypper']

# See https://github.com/gopasspw/gopass/issues/1849#issuecomment-802789285
- name: Install gopass on Debian
  when: ansible_facts.os_family == 'Debian'
  become: yes
  block:
  - name: Fetch gopass repo keyring
    ansible.builtin.get_url:
      url: https://packages.gopass.pw/repos/gopass/gopass-archive-keyring.gpg
      dest: /usr/share/keyrings/gopass-archive-keyring.gpg
  - name: Add gopass repo
    ansible.builtin.apt_repository:
      repo: "deb [arch=amd64,arm64,armhf \
        signed-by=/usr/share/keyrings/gopass-archive-keyring.gpg] \
        https://packages.gopass.pw/repos/gopass stable main"
      state: present
  - name: Update apt-cache and install gopass package
    ansible.builtin.apt:
      name: gopass
      update_cache: yes

- name: Install on macOS
  when: ansible_facts.distribution == 'MacOSX'
  block:
    - name: MACOS | Find brew binary
      command: which brew
      register: brew_which

    - name: MACOS | Get owner of brew binary
      stat:
        path: "{{ brew_which.stdout }}"
      register: brew_stat

    - name: MACOS | Install package
      homebrew:
        name:
          - gnupg2
          - pass
          - gopass
        state: present
        update_homebrew: no
      become: yes
      become_user: "{{ brew_stat.stat.pw_name }}"
      # Newer versions of brew want to compile a package which takes a long time. Do not upgrade homebrew until a
      # proper solution can be found
      environment:
        HOMEBREW_NO_AUTO_UPDATE: True
