---
- name: Check for MPW binary
  ansible.builtin.stat:
    path: /usr/local/bin/mpw
  register: _mpw_binary_stat

- name: Install MPW
  when: (not _mpw_binary_stat.stat.exists) or (force_reinstall | default(false))
  block:
    - name: Install build dependencies on Fedora
      when: ansible_distribution == "Fedora"
      become: true
      ansible.builtin.dnf:
        name:
          - libsodium-devel
        state: present

    - name: Create temporary build directory
      ansible.builtin.tempfile:
        prefix: ansible.build.mpw
        state: directory
      register: _mpw_build_dir

    - name: Download MPW source
      ansible.builtin.git:
        repo: https://gitlab.com/MasterPassword/MasterPassword.git
        version: 344771db
        recursive: false  # does *not* clone submodules
        dest: "{{ _mpw_build_dir.path }}"

    # God I hate this
    - name: Patch .gitmodules to use HTTPS
      ansible.builtin.replace:
        path: "{{ _mpw_build_dir.path }}/.gitmodules"
        regexp: "url = git://"
        replace: "url = https://"

    - name: Initialize submodules
      ansible.builtin.command:
        cmd: git submodule update --init
        chdir: "{{ _mpw_build_dir.path }}"

    - name: Build MasterPassword binary
      ansible.builtin.command:
        cmd: bash build
        chdir: "{{ _mpw_build_dir.path }}/platform-independent/cli-c/"

    - name: Copy binary to system path
      become: true
      ansible.builtin.copy:
        remote_src: true
        src: "{{ _mpw_build_dir.path }}/platform-independent/cli-c/mpw"
        dest: "/usr/local/bin"
        mode: 0755
  always:
    - name: Remove temporary directory
      ansible.builtin.file:
        path: "{{ _mpw_build_dir.path }}"
        state: absent
