---
- name: Check whether binary exists
  become: true
  ansible.builtin.stat:
    path: "~{{ local_username }}/.local/bin/MultiMC"
  register: _multimc_stat

- name: Install MultiMC
  when: (not _multimc_stat.stat.exists) or (force_reinstall | default(false))
  block:
    - name: Create temp dir
      ansible.builtin.tempfile:
        state: directory
      register: _multimc_tempdir

    - name: Download and unpack distribution archive
      ansible.builtin.unarchive:
        src: https://files.multimc.org/downloads/mmc-stable-lin64.tar.gz
        remote_src: true
        dest: "{{ _multimc_tempdir.path }}"

    - name: Ensure ~/.local/share/ exists
      become: true
      ansible.builtin.file:
        path: ~{{ local_username }}/.local/share
        state: directory
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0700

    - name: Ensure ~/.local/bin/ exists
      become: true
      ansible.builtin.file:
        path: ~{{ local_username }}/.local/bin
        state: directory
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0700

    - name: Copy MMC distribution to ~/.local/share/
      become: true
      ansible.builtin.copy:
        remote_src: true
        src: "{{ _multimc_tempdir.path }}/MultiMC/"
        dest: "~{{ local_username }}/.local/share/multimc"
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0700

    - name: Link MMC binary into ~/.local/bin/
      become: true
      ansible.builtin.file:
        state: link
        src: ~{{ local_username }}/.local/share/multimc/MultiMC
        path: ~{{ local_username }}/.local/bin/MultiMC

    - name: Copy application icon
      become: true
      ansible.builtin.copy:
        src: multimc.png
        dest: ~{{ local_username }}/.local/share/icons/multimc.png
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0755

    - name: Template application desktop entry
      become: true
      ansible.builtin.template:
        src: multimc.desktop.j2
        dest: ~{{ local_username }}/.local/share/applications/multimc.desktop
        owner: "{{ local_username }}"
        group: "{{ local_username }}"
        mode: 0755

  always:
    - name: Delete temp dir
      ansible.builtin.file:
        path: "{{ _multimc_tempdir.path }}"
        state: absent
