---
- name: Manage GNOME extension
  vars:
    requested_git_tag: "{{ git_tag }}"
    extension_name: "{{ ext_name }}"
    extension_url: "{{ ext_url }}"
    extension_path: "{{ ansible_user_dir }}/.local/share/gnome-shell/extensions/{{ ext_id }}"
    version_file: "{{ extension_path }}/version.txt"
  block:
    - name: Check if extension is installed
      ansible.builtin.stat:
        path: "{{ extension_path }}"
      register: ext_check

    - name: Read last installed version
      ansible.builtin.slurp:
        src: "{{ version_file }}"
      register: installed_version
      ignore_errors: true
      when: ext_check.stat.exists

    - name: Determine if update is needed
      ansible.builtin.set_fact:
        update_needed: >-
          {{ installed_version.content is not defined or
              (installed_version.content | b64decode | trim != requested_git_tag) }}

    - name: Delete old extension if updating
      ansible.builtin.file:
        path: "{{ extension_path }}"
        state: absent
      when: update_needed

    - name: Create directory for extension
      ansible.builtin.file:
        path: "{{ extension_path }}"
        state: directory
        mode: '0755'
      when: not ext_check.stat.exists or update_needed

    - name: Download extension
      ansible.builtin.get_url:
        url: "{{ extension_url | replace('%TAG%', requested_git_tag) }}"
        dest: "{{ extension_path }}/release.zip"
        mode: '0644'
      when: update_needed or not ext_check.stat.exists

    - name: Extract extension
      ansible.builtin.unarchive:
        src: "{{ extension_path }}/release.zip"
        dest: "{{ extension_path }}"
      when: update_needed or not ext_check.stat.exists

    - name: Store installed version of the extension
      ansible.builtin.copy:
        content: "{{ requested_git_tag }}"
        dest: "{{ version_file }}"
        mode: '0644'
      when: update_needed or not ext_check.stat.exists

    - name: Cleanup post installation
      ansible.builtin.file:
        path: "{{ extension_path }}/release.zip"
        state: absent
      when: not ext_check.stat.exists or update_needed

    - name: Notify user of required GNOME Shell reload
      ansible.builtin.debug:
        msg: >
          Please reload GNOME Shell by pressing Alt + F2, typing 'r' and pressing Enter.
          Then enable the {{ extension_name }} in GNOME Tweaks.
          Or on Wayland, log out and back in.
      when: not ext_check.stat.exists or update_needed
